面试金典系列1--确定两串乱序同构
给定两个字符串,请编写程序,确定其中一个字符串的字符重新排列后,能否变成另一个字符串。这里规定大小写为不同字符,且考虑字符串重点空格。
给定一个string stringA和一个string stringB,请返回一个bool,代表两串是否重新排列后可相同。保证两串的长度都小于等于5000。
测试样例:
"This is nowcoder","is This nowcoder"
返回:true
"Here you are","Are you here"
返回:false
解法:
import java.util.*;
public class Same {
public boolean checkSam(String stringA, String stringB) {
// write code here
if (stringA == null || stringA.length() < 1 || stringB == null || stringB.length() < 1
|| stringA.length() != stringB.length()) {
return false;
}
boolean resu = true;
HashMap<Character, Integer> mapA = getMap(stringA);
HashMap<Character, Integer> mapB = getMap(stringB);
for (Map.Entry<Character, Integer> entry : mapA.entrySet()) {
char key = entry.getKey();
int value = entry.getValue();
if (!mapB.containsKey(key) || value != mapB.get(key)) {
resu = false;
break;
}
}
return resu;
}
public HashMap<Character, Integer>getMap(String str) {
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); ++i) {
Integer tmp = map.get(str.charAt(i));
tmp = (tmp == null) ? new Integer(1) : (tmp + 1);
map.put(str.charAt(i), tmp);
}
return map;
}
}