題目
寫出一個函數(shù) anagram(s, t)
判斷兩個字符串是否可以通過改變字母的順序變成一樣的字符串。
樣例
給出 s = "abcd",t="dcab",返回 true
給出 s = "ab", t = "ab", 返回 true.
給出 s = "ab", t = "ac", 返回 false.
分析
這種題目只需判斷是否具有相同的字符,以及字符的數(shù)量是否相等
技巧是新建一個數(shù)組用于記錄,若有就加一,多個就繼續(xù)加一
再在另一個字符串里減一,最后如果碰到小于0的,就說明字符數(shù)不相等或者沒有
代碼
public class Solution {
/**
* @param s: The first string
* @param b: The second string
* @return true or false
*/
public boolean anagram(String s, String t) {
// write your code here
if(s.length() != t.length())
return false;
int[] count = new int[256];
for (int i = 0; i < s.length(); i++) {
count[(int) s.charAt(i)]++;
}
for (int i = 0; i < t.length(); i++) {
count[(int) t.charAt(i)]--;
if(count[(int) t.charAt(i)] < 0)
return false;
}
return true;
}
};