Write a method anagram(s,t)
to decide if two strings are anagrams or not.
What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.
Example
Given s = "abcd"
, t = "dcab"
, return true
.
Given s = "ab"
, t = "ab"
, return true
.
Given s = "ab"
, t = "ac"
, return false
.
Challenge
O(n) time, O(1) extra space
思路:两串字符串分别统计每个出现字符的个数,如果有个数不等的,就不是anagram,反之
public class Solution {
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
public boolean anagram(String s, String t) {
Map<Character,Integer> mapS=new HashMap<>();
Map<Character,Integer> mapT=new HashMap<>();
for(int i=0;i<s.length();i++){
char ch=s.charAt(i);
if(!mapS.containsKey(ch)){
mapS.put(ch,1);
}else{
mapS.put(ch,mapS.get(ch)+1);
}
}
for(int i=0;i<t.length();i++){
char ch=t.charAt(i);
if(!mapT.containsKey(ch)){
mapT.put(ch,1);
}else{
mapT.put(ch,mapT.get(ch)+1);
}
}
for(int i=0;i<s.length();i++){
char ch=t.charAt(i);
if(mapS.get(ch)!=mapT.get(ch)){
return false;
}
}
return true;
}
}
方法二:统计一个字符串里每个字符出现的个数,在统计另一个字符串字符的时候,个数- -,如果哪个字符的的总数不为0就false,反之。
public class Solution {
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
public boolean anagram(String s, String t) {
if(s.length()!=t.length()){
return false;
}
int[] count=new int[256];
for(int i=0;i<s.length();i++){
count[s.charAt(i)]++;
}
for(int i=0;i<t.length();i++){
count[t.charAt(i)]--;
}
for(int i=0;i<count.length;i++){
if(count[i]!=0){
return false;
}
}
return true;
}
}
思路代码一样的55. Compare Strings :点击打开链接
public class Solution {
/**
* @param A : A string includes Upper Case letters
* @param B : A string includes Upper Case letter
* @return : if string A contains all of the characters in B return true else return false
*/
public boolean compareStrings(String A, String B) {
int[] count=new int[26];
for(int i=0;i<A.length();i++){
count[A.charAt(i)-'A']++;
}
for(int i=0;i<B.length();i++){
count[B.charAt(i)-'A']--;
}
for(int i=0;i<count.length;i++){
if(count[i]<0){
return false;
}
}
return true;
}
}