【09_242】Valid Anagram
Valid Anagram
My SubmissionsTotal Accepted: 43694 Total Submissions: 111615 Difficulty: Easy
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?
这个方法可以把包括unicode characters在内的都进行对比。
对string的内部进行排序,这个方法要记住!
这个方法的头函数是#include <algorithm>
C++写法:
1 class Solution { 2 public: 3 bool isAnagram(string s, string t) { 4 sort(s.begin(), s.end()); 5 sort(t.begin(), t.end()); 6 if (s == t) 7 return true; 8 else 9 return false; 10 } 11 };
我的解法时间太长,下面是Discuss里面的几种简单解法:
- The idea is simple. It creates a size 26 int arrays as buckets for each letter in alphabet. It increments the bucket value with String s and decrement with string t. So if they are anagrams, all buckets should remain with initial value which is zero. So just checking that and return
1 public class Solution { 2 public boolean isAnagram(String s, String t) { 3 int[] alphabet = new int[26]; 4 for (int i = 0; i < s.length(); i++) alphabet[s.charAt(i) - 'a']++; 5 for (int i = 0; i < t.length(); i++) alphabet[t.charAt(i) - 'a']--; 6 for (int i : alphabet) if (i != 0) return false; 7 return true; 8 } 9 }
看了别的解答发现,核心思想都一样,但是语句表达上各有千秋,有的很简单比如上面的要学习。