[leetcode] 242. Valid Anagram

임택·2021년 2월 12일
0

알고리즘

목록 보기
24/63

problem

code

    public boolean isAnagram(String s, String t) {
        if(s.length() == 0 && t.length() == 0) return true;
        if(s.length() != t.length()) return false;
        return this.sortStr(s).equals(this.sortStr(t));
     }
    
    public String sortStr(String x) {
        char[] arr = x.toCharArray();
        Arrays.sort(arr);
        return String.valueOf(arr);
    }

Time: O(nlogn) => sorting nlogn, comparing n: nlogn
Space: O(n) or O(1) => some languages, a string is an char array

using hash? counter table

public boolean isAnagram(String s, String t) {
	if (s.length() != t.length()) return false;
    
    int[] table = new int[26] // cuz only lower case
    for (int i = 0; i < s.length(); i++) {
    	table[s.charAt(i) - 'a']++;
    }
    for (int i = 0; i < t.length(); i++) {
    	table[t.charAt(i) - 'a']--;
        if(table[t.charAt(i) - 'a'] < 0) return false;
    }
    return true;
}

Time: O(n)
Space: O(1), cuz we use only 26 and it never differs no matther how large n is, so constant

profile
캬-!

0개의 댓글