两个字符串是变位词
写出一个函数 anagram(s, t)
去判断两个字符串是否是颠倒字母顺序构成的
样例
给出 s="abcd"
,t="dcba"
,返回ture
未采用数据结构的写法:
public class Solution {
/**
* @param s: The first string
* @param t: The second string
* @return true or false
*/
public boolean anagram(String s, String t) {
// write your code here
int a = s.length();
int b = t.length();
if (a != b){
return false;
}
for (int i = 0; i < a; i++){
char m = s.charAt(i);
int num = 0; //标记值
for (int j = 0; j < a; j++){
if (t.charAt(j) == m){
num = 1;
}
}
if (num == 1){
continue;
} else {
return false;
}
}
return true;
}
};
此种解法实际是有错误的,比如"abbb"
,"baaa"
会被误认为是变位词,实际未然。
利用hash表对字符串存储,可得到理想的结果。代码如下:
import java.util.*;
public class test{
public boolean compareStrings(String A, String B) {
test cs = new test();
if(B.length() > A.length())
return false;
Map<Character,Integer> aMap = cs.StringToMap(A);
for(int i = 0; i < B.length(); i++){
char b = B.charAt(i);
if (aMap.containsKey(b)){
if(aMap.get(b) > 1){
int times = aMap.get(b)-1;
aMap.put(b, times);
}else
aMap.remove(b);
}else
return false;
}
return true;
}
public Map<Character,Integer> StringToMap(String S){
Map<Character,Integer> sMap = new HashMap<Character,Integer>();
for(int i = 0; i < S.length();i++){
char a = S.charAt(i);
if(sMap.containsKey(a)){
int times = sMap.get(a)+1;
sMap.put(a, times);
}else
sMap.put(a, 1);
}
return sMap;
}
public static void main(String []args){
test cst = new test();
boolean c = cst.compareStrings("aaadbb", "dbaaba");
System.out.print(c);
}
}
函数StringToMap
完成的功能是将字符串存储在hash表中,且返回一个对应的map映射。
比如StringToMap("lint")
,返回的map<Character,Integer>
映射为{t=1, n=1, l=1, i=1}
。
StringToMap("aaadbb")
返回的map
映射为{d=1,b=2,a=3}
;
(不过此处put函数为何按照字母从大到小放入到map中呢?不解)
compareStrings()
的思路其实同StringToMap()
函数。
算法复杂度是O(n)
吧。