您的位置:首页 > 其它

Lintcode—(1)两个字符串是变位词

2017-02-10 15:06 260 查看
写出一个函数 
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;
}
}
}
};

解题思路:

两个相同长度的字符串,一个转换成相应数组,另一个遍历里面的字符一个一个看是不是在数组里面。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: