Leetcode-204-Valid Anagram

superorange 2022/07/13 462Views

Valid Anagram

leetcode: https://leetcode.com/problems/valid-anagram/

Description:

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Idea:

solution1: use sorted api

Code:

class Solution {
    public boolean isAnagram(String s, String t) {
         if (s.length() != t.length()) {
            return false;
         }
        char[] sa = s.toCharArray();
        char[] ta = t.toCharArray();
        Arrays.sort(sa);
        Arrays.sort(ta);
      //return new String(ta).equals(new String(sa));
        return Arrays.equals(sa,ta);
    }
}

**solution 2: **

Step1: use array(simple hash table) to record each alphabet and the corresponding occurrences

Step2: record first string with the array, and then decrease value of the each index when record the second string

Step3: if all element’s value is 0 in the array, it means two strings are anagram.

Code:

class Solution {
    public boolean isAnagram(String s, String t) {
        //if two string's length is not equal, return false
         if (s.length() != t.length()) {
            return false;
         }
        //create a array with the size is 26(alphabet is 26 letters)
        int[] result = new int[26]; 
        //record each letter and the corresponding times with increase
        for(char x:s.toCharArray()){
        //get index by calculate ASCII
            result[x - 'a'] += 1; 
        }
        //record the other string, with decrease
        for(char y:t.toCharArray()){
            result[y - 'a'] -= 1; 
        }
        //verify each element's value of the array
        for(int i:result){
            if(i!=0){
                return false;
            }
        }
        return true;
    }
}
 result[x - 'a']
 //calculate the ASCII value