【Leetcode】Valid Anagram

题目链接:https://leetcode.com/problems/valid-anagram/

题目:

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

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

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

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

思路:

用HashMap存储s的字符和它出现次数的关系,遍历字符串t并减去hashmap中存储的相应的字符出现的次数,如果t中有字符不包含在hashmap中返回false,最后如果hashmap中value有不为0的,则返回false,否则返回true。本题因为是小写字母可以用26位数组表示对应字母出现的次数。实质也是hashmap的思想。

算法:

	public boolean isAnagram(String s, String t) {
		int count[] = new int[26];
		if (s.length() != t.length()) {
			return false;
		}
		if (s.equals(t)) {
			return true;
		}
		char ss[] = s.toCharArray();
		char tt[] = t.toCharArray();
		for (char tmp : ss) {
			count[tmp - 'a']++;
		}
		for (char tmp : tt) {
			count[tmp - 'a']--;
		}
		for (int i : count) {
			if (i != 0) {
				return false;
			}
		}
		return true;
	}


你可能感兴趣的:(【Leetcode】Valid Anagram)