158. 两个字符串是变位词
写出一个函数 anagram(s, t) 判断两个字符串是否可以通过改变字母的顺序变成一样的字符串。
样例
样例 1:
输入: s = "ab", t = "ab"
输出: true
样例 2:
输入: s = "abcd", t = "dcba"
输出: true
样例 3:
输入: s = "ac", t = "ab"
输出: false
挑战
O(n) 的时间复杂度, O(1) 的额外空间
说明
什么是 Anagram?
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
if (s==null&&t==null)return true;
if (s==null||t==null||s.length()!=t.length())return false;
char[] sArrays=s.toCharArray();
char[] tArrays=t.toCharArray();
for (int i = 0; i < sArrays.length; i++) {
boolean has=false;
for (int j = i; j < tArrays.length; j++) {
if (sArrays[i]==tArrays[j]){
tArrays[j]=tArrays[i];
has=true;
break;
}
}
if (!has)return false;
}
return true;
}
}