Java Anagrams

  • + 0 comments

    My solution :)

    static boolean isCharConsidered(char[] chs, char ch) {
          for(int i = 0; i < chs.length; i++) {
            if(chs[i] == ch)
              return true;
          }
          return false;
        }
        
        static int getCntOfChar(byte[] chs, char ch) {
          int res = 0;
          for(int i = 0; i < chs.length; i++) {
            if(chs[i] == ch)
              res++;
          }
          return res;
        }
        
        static boolean isAnagram(String a, String b) {
    
          if(a.length() != b.length())
            return false;
          
          // Complete the function
          byte[] acs = a.toLowerCase().getBytes();
          byte[] bcs = b.toLowerCase().getBytes();
    
          int nextChar = 0;
          char[] chars = new char[a.length()];
    
          for(int i = 0; i < a.length(); i++) {
            if(!isCharConsidered(chars, a.charAt(i))){
              chars[nextChar++] = a.charAt(i);
              if (getCntOfChar(acs, a.charAt(i)) != getCntOfChar(bcs, a.charAt(i)))
                return false;
            }
          }
    
          return true;
        }