String Construction

Sort by

recency

|

989 Discussions

|

  • + 0 comments

    Java Code using HashSet

    public static int stringConstruction(String s) {
        
            Set<Character> set = new HashSet<>();
            for (char c : s.toCharArray()) {
                set.add(c);
            }
            return set.size();
        }
    
  • + 0 comments

    The solution here is to count the number of unique occurrences of the characters, here is the explanation : https://youtu.be/UqqNcIUnsv8

    solution 1 : using map

    int stringConstruction(string s) {
        map<char, int> mp;
        int r = 0;
        for(int i = 0; i < s.size(); i++) if(!mp[s[i]]){
            mp[s[i]] = 1; r++;
        }
        return r;
    }
    

    solution 2 : using set

    int stringConstruction(string s) {
        set<char> se(s.begin(), s.end());
        return se.size();
    }
    
  • + 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();
        }
    
  • + 0 comments
    def stringConstruction(s):
        return len(set(s))
    
  • + 0 comments
    def stringConstruction(s):
        return len(set(s))