【09_242】Valid Anagram

时间:2023-03-09 04:09:45
【09_242】Valid Anagram

Valid Anagram

My Submissions

Question
Total 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++写法:

 class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(), s.end());
sort(t.begin(), t.end());
if (s == t)
return true;
else
return false;
}
};

我的解法时间太长,下面是Discuss里面的几种简单解法:

  1. 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
 public class Solution {
public boolean isAnagram(String s, String t) {
int[] alphabet = new int[26];
for (int i = 0; i < s.length(); i++) alphabet[s.charAt(i) - 'a']++;
for (int i = 0; i < t.length(); i++) alphabet[t.charAt(i) - 'a']--;
for (int i : alphabet) if (i != 0) return false;
return true;
}
}

  

看了别的解答发现,核心思想都一样,但是语句表达上各有千秋,有的很简单比如上面的要学习。