题目:
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.
分析:
判别“anagram”的条件:
1. 两个字符完全相等,两数完全为空: true
2. 两个字符不等长:false
3. 同一个字符出现的次数不相等:false
代码如下:
public class Solution { public static int hasCharacter(String Basic, String Target){ for(int i = 0;i<Basic.length();i++){ if(Basic.substring(i, i+1) == Target ){ return i; } } return -1; } public static boolean isAnagram(String s, String t) { if(s.length() != t.length()){ return false; } if(s == t){ return true; } for(int i=0;i<t.length();i++){ int iFlag = hasCharacter(s,t.substring(i, i+1)); if(iFlag == -1){ return false; } else{ s = s.substring(iFlag,iFlag+1); } } return true; } }
高手的思路:将两个字符转换成字符串,然后排序后比较即可
public static boolean isAnagram(String s, String t) { if(s == t || (s.equals("") && t.equals(""))){ return true; } if(s.length() != t.length()){ return false; } char[] charS = s.toCharArray(); char[] charT = t.toCharArray(); Arrays.sort(charS); Arrays.sort(charT); return charS.equals(charT); }