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.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
分析:本题是判断两个字符串是否是顺序不同,所包含字母相同的字符串。马上想到数组的sort()方法可以解决类似问题。
代码:下面两段代码,第一段是错误的,第二段是正确的。
public class Solution { public boolean isAnagram(String s, String t) { String [] sArr = s.split(""); String [] tArr = t.split(""); Arrays.sort(sArr); Arrays.sort(tArr); StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); for(int i = 0; i < sArr.length; i++){ sb1.append(sArr[i]); } for(int i = 0; i < tArr.length; i++){ sb2.append(tArr[i]); } return sb1.equals(sb2); } }
public class Solution { public boolean isAnagram(String s, String t) { char [] sArr = s.toCharArray(); char [] tArr = t.toCharArray(); Arrays.sort(sArr); Arrays.sort(tArr); return String.valueOf(sArr).equals(String.valueOf(tArr)); } }