-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path242. Valid Anagram
32 lines (31 loc) · 1.19 KB
/
242. Valid Anagram
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*基本思路就是先把原先的string按照character排序,然后进行比较。 toCharArray 可以把string转换成char数组,
Arrays.sort(ch); can sort char[] ch alphabetically
String.valueOf(ch ) can change the char array ch[] to a string
*/
public class Solution {
public boolean isAnagram(String s, String t) {
char[] stoChar= s.toCharArray();
char[] ttoChar=t.toCharArray();
Arrays.sort(stoChar);
Arrays.sort(ttoChar);
String sorteds=String.valueOf(stoChar);
String sortedt=String.valueOf(ttoChar);
return sorteds.equals(sortedt);
}
}
第二种方法,注意java for里面i需要声明的,总忘。。。。还有charAt()了解一下 unicode8最多只有256所以i的范围取256
public class Solution {
public boolean isAnagram(String s, String t) {
if(s==null| t==null|s.length()!=t.length())
return false;
int lookup[]=new int[256];
for (int i=0;i<s.length();i++) //be careful it is not 256, it is s.length(0
{lookup[(int)(s.charAt(i))]++;
lookup[(int)(t.charAt(i))]--;
}
for(int i=0;i<256;i++)
if(lookup[i]!=0)
return false;
return true;
}
}