LeetCode-242~Valid Anagram

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?
给定两个字符串,判断t是否是s的异位构词

算法分析

异位构词:具体可参考维基百科,将一个词的或句子中的字母重新排列,原文中每个字母只能使用一次,构成一个新的词或句子。

方法一(排序):

将给定的字符串转换为数组,排序,判断两个数组是否相等即可。

Java代码
public class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;

        char[] s_array = s.toCharArray();
        char[] t_array = t.toCharArray();
        
        Arrays.sort(s_array);
        Arrays.sort(t_array);
        
        return Arrays.equals(s_array, t_array);
    }
}
方法二:

通过一个数组记录已经出现的字母的个数。如果为负,return false

Java代码
public class Solution {
    public boolean isAnagram(String s, String t) {
        if (s.length() != t.length()) return false;

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

参考

  • LeetCode
  • 维基百科

你可能感兴趣的:(LeetCode-242~Valid Anagram)