String Construction

  • + 0 comments

    My Java solution:

    public static int stringConstruction(String s) {
            // goal: determine min cost of copying string s
            if(s.length() == 1) return 1;
            //this solution has o(n) time, o(n) space
            
            Set<Character> characterSet = new HashSet<>();
            //iterate over each char in s
            for(char c: s.toCharArray()){
                //if char isnt in char set, add to the total cost
                if(!characterSet.contains(c)){
                    characterSet.add(c); //add char into char set
                }
            }
            return characterSet.size();
        }