Sort by

recency

|

966 Discussions

|

  • + 0 comments

    My c++ solution using map, here is the explanation : https://youtu.be/0-xHzWDVAME

    int anagram(string s) {
        if(s.size() % 2 == 1) return -1;
        map<char, int> mp;
        int ans = 0;
        for(int i = 0; i < s.size() / 2; i++) mp[s[i]]++;
        for(int i = s.size() / 2; i < s.size(); i++){
            if(mp[s[i]] != 0) mp[s[i]]--;
            else ans++;
        }
        return ans;
    }
    
  • + 0 comments

    Thank you so much for help.

  • + 0 comments

    Perl:

    sub anagram {
        my $s = shift;
        my %h1;
        my $cnt = 0;
    
        if (length($s) % 2) {
            return -1;
        }
    
        my $s1 = substr($s, 0, length($s) / 2);
        my @s2 = split("", substr($s, length($s) / 2, length($s)));
    
        
        foreach (split("", $s1)) {
            $h1{$_} += 1;
        }
    
        foreach my $k (@s2) {
            if (defined($h1{$k}) && $h1{$k} != 0) {
                $h1{$k} -= 1;            
            }
            else {
                $cnt++;
            }        
        }
    
        return $cnt;
    }
    
  • + 0 comments

    My answer with Typescrip

    function anagram(s: string): number {
        // 0. check s length is odd, so it cann't be split, return -1
        if (s.length % 2 != 0) return -1
    
        // 1. split [s] into left part [l] and right part [r], define [m]&[o] to count
        let l = s.substring(0, s.length / 2)
        let r = s.substring(s.length / 2)
        let m = new Map<string, number>()
        let o = 0
    
        // 2. count [l] into [m], check [r], count++
        for (let c of l) m.set(c, (m.get(c) || 0) + 1)
        for (let c of r) {
            if (m.has(c) && m.get(c) > 0) m.set(c, m.get(c) - 1)
            else o++
        }
    
        // 3. return [o]
        return o
    }
    
  • + 0 comments
    from collections import Counter
    
    def anagram(s):
        n = len(s)
        if n % 2 == 1:
            return -1  
        a = s[:n//2]
        b = s[n//2:]
        freq_a = Counter(a)
        freq_b = Counter(b)
        changes = 0
        for char in freq_a:
            if freq_a[char] > freq_b.get(char, 0):
                changes += freq_a[char] - freq_b.get(char, 0)
        return changes