String Construction

Sort by

recency

|

983 Discussions

|

  • + 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
    def stringConstruction(s):
         return len(list(set(s)))
    

    or

    def stringConstruction(s):
        bitmask = 0
        for char in s:
            bitmask |= (1 << (ord(char) - ord('a')))
        return bin(bitmask).count('1')
    
  • + 0 comments

    My answer with Typescript,

    function stringConstruction(s: string): number {
        // count number of unique character in [s]
        return new Set(s.split('')).size
    }
    
  • + 0 comments

    Perl:

    sub existElement {
        my $element = shift;
        my $arr = shift;
        for (my $i = 0; $i <= scalar(@$arr) - 1; $i++){
            if ($arr->[$i] eq $element) {
                return ($arr->[$i] eq $element) ? 1 : 0;
                last;
            }        
        }
    }
    
    sub stringConstruction {
        my @s = split("", shift);
        my $res = [0];
        my $cnt = 0;
        foreach my $el (@s) {
            if (!existElement($el, $res)) {
                push(@$res, $el);
                $cnt++;
            }        
        }
        return $cnt;
    }
    
  • + 0 comments

    Java:

    public static int stringConstruction(String s) {
      boolean[] freqs = new boolean[26]; // a to z
      int cost = 0;
      for (char c : s.toCharArray()) {
        // If the character hasn't been added before, increase the cost
        if (!freqs[c - 'a']) {
          freqs[c - 'a'] = true;
          cost++;
        }
      }
      return cost;
    }