写出一个函数 anagram(s, t)
判断两个字符串是否可以通过改变字母的顺序变成一样的字符串。
样例
给出 s = "abcd"
,t="dcab"
,返回 true
.
给出 s = "ab"
, t = "ab"
, 返回 true
.
给出 s = "ab"
, t = "ac"
, 返回 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) {
// write your code here
if(s.length() != t.length())
return false;
Linkedlist list = new Linkedlist();
for(int i=1;i<=s.length();i++){
list.add(s.substring(i, i+1));
}
for(int j=1;j<t.length();j++){
if(list.length() == null)
return false;
if(list.contains(t.substring(j, j+1))){
list.remove(t.substring(j, j+1));
}else{
return false;
}
}
}
};
解题思路:
两个相同长度的字符串,一个转换成相应数组,另一个遍历里面的字符一个一个看是不是在数组里面。