Header Ad

Leetcode Valid Anagram problem solution

In this Leetcode Valid Anagram problem solution we have given two strings s and t, return true if t is an anagram of s, and false otherwise.

Leetcode Valid Anagram problem solution


Problem solution in Python.

from collections import Counter
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return Counter(s) == Counter(t)



Problem solution in Java.

public boolean isAnagram(String s, String t) {
    int len1=s.length(),len2=t.length();
    if(s==null||t==null||len1!=len2)
      return false;
      HashMap<Character,Integer> map=new HashMap<Character,Integer>();
      for(int i=0;i<len1;i++){
          char c=s.charAt(i);
          if(map.get(c)==null)
            map.put(c,1);
          else
            map.put(c,map.get(c)+1);
      }
      
      for(int i=0;i<len2;i++){
          char c=t.charAt(i);
          if(map.get(c)==null)
            return false;
          else{
            int num=map.get(c);
            if(num==0)
              return false;
            else
              map.put(c,map.get(c)-1);
          }
      }
      
     return true;
}


Problem solution in C++.

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size()!=t.size()) return false;
        int count[26]={0};
        for(int i=0;i<s.size();i++) 
            count[s[i]-'a']++;
        for(int i=0;i<s.size();i++){
            count[t[i]-'a']--;
            if(count[t[i]-'a']<0) return false;
        }
        return true;
    }
};


Problem solution in C.

bool isAnagram(char * s, char * t){ 
    unsigned long long s1 = 0, s2 = 0, p1 = 1, p2 = 1;  
    for (; *s && *t ; s1 += *s, s2 += *t, p1 *= *s++, p2 *= *t++);
    return !*s && !*t && s1 == s2 && p1 == p2;
}


Post a Comment

0 Comments