leetcode [#242]

目录

题目

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

Example:
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

Note:
You may assume the string contains only lowercase alphabets.


解决方案

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
public class Solution {
public static boolean isAnagram(String s, String t) {
boolean result = true;
int sLen = s.length();
int tLen = t.length();
if(sLen != tLen){
result = false;
} else {
char[] arrayS = sortStr(s);
char[] arrayT = sortStr(t);
for(int i = 0 ; i < arrayS.length ; i++){
if(arrayS[i] != arrayT[i]){
result = false;
break;
}
}
}
return result;
}

private static char[] sortStr(String str){
int N = str.length();
char[] a = new char[N];
for(int k=0; k<N; k++){
a[k] = str.charAt(k);
}
Arrays.sort(a);
return a;
}
}

注意事项

  1. 两个字符串互为字谜,首先长度要一样。
  2. 将两个字符串排序,只要对应位不一样,则肯定不是互为字谜。