您的位置:首页 > 其它

题目 :两个字符串是变位词

2015-08-19 18:39 381 查看
写出一个函数
anagram(s, t)
去判断两个字符串是否是颠倒字母顺序构成的

您在真实的面试中是否遇到过这个题?

Yes

哪家公司问你的这个题?
Airbnb
Alibaba
Amazon Apple
Baidu Bloomberg
Cisco Dropbox
Ebay Facebook
Google Hulu
Intel Linkedin
Microsoft NetEase
Nvidia Oracle
Pinterest Snapchat
Tencent Twitter
Uber Xiaomi
Yahoo Yelp
Zenefits
感谢您的反馈

样例

给出 s=
"abcd"
,t=
"dcab"
,返回
true


标签 Expand

字符串处理

Cracking The Coding Interview

相关题目 Expand

2
(string),(hash-table)
中等 乱序字符串 22 %
1
(basic-implementation),(string),(lintcode-copyright)

容易 比较字符串 26 %

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;

}

boolean flag = true;

char ss[] = new char[s.length()];

char ts[] = new char[t.length()];

for(int i=0;i<s.length();i++){

ss[i] = s.charAt(i);

}

for(int i=0;i<t.length();i++){

ts[i] = t.charAt(i);

}

for(int i=0;i<s.length();i++){

int count = 0;

for(int j=0;j<s.length();j++){

if(ts[i]==ss[j]){

ss[j] = '1';

break;

}

count++;

}

if(count>s.length()-1){

flag = false;

}

}

return flag;

}

};

大神AC代码,在总共的256个字符中,若存在则为1。

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==null || t==null || s.length()!=t.length()) return false;
int[] ss = new int[256]; int[] tt = new int[256];
for (int i=0; i<256; j++) {
if (ss[j] != tt[j]) return false; }
return true;
}
};


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: