0.问题分析
即判断两个字符串中所有字符出现次数是否相同。
- 首先,如果两个字符串长度不同,那么两个字符串必定不是异位词。
- 其次,即统计完一个字符串后,对于另一个字符串遍历,过程中,如果有字符的出现次数小于0,显而,也必定false。
1.利用Map实现(有点蠢)
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()) {
return false;
}
Map<Character,Integer> map=new HashMap<>();
char key1,key2;
int value1,value2;
for(int i=0;i<s.length();i++){
key1=s.charAt(i);
if(!map.containsKey(key1)){
map.put(key1,1);
continue;
}
value1=map.get(key1);
map.put(key1,value1+1);
}
for(int i=0;i<t.length();i++){
key2=t.charAt(i);
if(!map.containsKey(key2)){
return false;
}
value2=map.get(key2);
if(value2-1<0){
return false;
}
map.put(key2,value2-1);
}
for(Integer i:map.values()){
if(i!=0){
return false;
}
}
return true;
}
}
2.利用数组
因为题目中规定一定是小写字母,那么出现情况必是’a’~'z’那么通过数组即可实现哈希表的作用。
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] counter = new int[26];
for (int i = 0; i < s.length(); i++) {
counter[s.charAt(i) - 'a']++;
counter[t.charAt(i) - 'a']--;
}
for (int count : counter) {
if (count != 0) {
return false;
}
}
return true;
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/valid-anagram/solution/you-xiao-de-zi-mu-yi-wei-ci-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
3.总结
熟悉各种各种数据结构的使用情况,在面对问题时,应考虑清楚你使用的数据结构合不合适!