p242

LeetCode p242 Valid Anagram 题解

1.题目:

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.

题意:

输入两个字符串判断这两个字符串的所有元素是否相同

2.解题思路:

借用了啊哈算法里面提到的桶排序

3.代码


[title] [] [url] [link text]
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
33
34
35
36
37
38
39
 
package leetcode;

import java.util.Hashtable;
import java.util.Scanner;
import java.util.SortedMap;

public class p242 {
public static void main(String[] args) {
String a = "anagram";
String b = "nagaram";
boolean ans = isAnagram(a, b);
System.out.println(ans);

}

public static boolean isAnagram(String s, String t) {

if (s.length()!=t.length()) return false;
int check[]=new int [26];
for (int i =0;i<check.length;i++)
{
check[i]=0;
}
for (int i=0;i<s.length();i++)
{
check[s.charAt(i)-'a']++;
check[t.charAt(i)-'a']--;
}
for (int i=0;i<check.length;i++)
{
if (check[i]!=0) return false;
//System.out.println(check[i]);
}
return true;
}

}


4.一些总结: