您的位置:首页 > 其它

leetcode_Valid Anagram

2015-08-06 21:28 309 查看
描述:

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Note:

You may assume the string contains only lowercase alphabets.
思路:

百度的意思anagram:由颠倒字母顺序而构成的字。

有两种解决方案,一个对字符串中的字符进行排序并判断排序后的字符串序列是否相同,另外一种方法是直接统计所有字符出现的次数并判断所有字符出现的次数是否相同,相同则返回true

1.将字符串中字符进行排序肯定涉及到String转换位charArray,然后用nlogn的算法对字符进行排序,既用到额外存储空间,用得话费nlogn的时间

2.直接生成一个26个整型数组,统计所有字符出现的次数并比较各个字符出现的次数是否相同。O(k)的空间复杂度,O(n)的时间复杂度

3.综上所述,方法2更胜一筹。

代码:

public boolean isAnagram(String s, String t) {
if(s==null&&t==null)
return true;
if(s==null||t==null)
return false;
int lens=s.length();
int lent=t.length();
if(lens!=lent)
return false;
int charCount1[]=new int[26];
int charCount2[]=new int[26];
for(int i=0;i<lens;i++)
{
++charCount1[s.charAt(i)-'a'];
++charCount2[t.charAt(i)-'a'];
}
for(int i=0;i<26;i++)
{
if(charCount1[i]!=charCount2[i])
return false;
}
return true;

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