1. 程式人生 > >[leetcode]242.Valid Anagram

[leetcode]242.Valid Anagram

代碼 ase return pre 不一致 charat lee sum function

題目

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true
Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

解法

思路

這個題的意思是:字符串s和t是否是由相同的字符構成:比如s中有2個a, 4個b,t中如果一樣,就稱s和t是anagram。
如果s和t長度不一致,則直接返回false。
因為題目中假設所有字母都是小寫,所以我們用一個長度為26的int數組,用每個元素來存s和t中每個字符的個數。s中如果存在,則++;t中如果存在,則--;這樣的話,遍歷到最後,如果s和t完全相同,那麽數組中的每個元素應該都為0。

代碼

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()) return false;
        int[] count = new int[32];
        for(int i = 0; i < s.length(); i++) {
            count[s.charAt(i) - ‘a‘]++;
            count[t.charAt(i) - ‘a‘]--;
        }
        
        for(int i:count)
            if(i != 0) return false;
        
        return true;
    }
}

[leetcode]242.Valid Anagram