Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
The answer is the count of distinct characters.
If the string does not contain a specific character, only then it costs 1 dollar. Because one character is a substring. When we are able to find it in a partially created string, it does not cost anything.
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.*; public class StringConstruction { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = Integer.parseInt(stdin.nextLine()); for(int i = 0; i < tests; i++) { String s = stdin.nextLine(); System.out.println(cost(s)); } stdin.close(); } private static int cost(String s) { char[] chars = s.toCharArray(); Map<Character, Boolean> charMap = new HashMap<>(); for(int i = 0; i < chars.length; i++) { charMap.put(chars[i], true); } return charMap.size(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
'use strict'; const processData = input => { const lines = input.split('\n'); for(let i = 1; i < lines.length; i++) { console.log(cost(lines[i])); } }; const cost = (s) => { const charMap = new Map(); for(let i = 0; i < s.length; i++) { charMap.set(s[i], true); } return charMap.size; }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Scala
1 2 3 4 5 6 |
object StringConstruction extends App { val lines = Source.stdin.getLines() val strings = lines.toList.tail val costs = strings.map(_.distinct.length) println(costs.mkString("\n")) } |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 |
def cost(s) map = Hash.new for i in 0...(s.size) map[s[i]] = true end map.size end n = gets.to_i n.times do s = gets.to_s.strip puts cost(s) end |