[leetcode]242.Valid Anagram

题目

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;
    }
}
posted @ 2018-10-14 11:36  shinjia  阅读(76)  评论(0编辑  收藏  举报