Valid Anagram --Nice

题目描述

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.
判断是否是换位构词

题目解答

解题思路

  • 先对字符数组排序,然后判断时候相等
  • 建立小写字符的hash表

代码实现

排序

public class Solution {
    public boolean isAnagram(String s, String t) {
        if(s == null || t == null)
            return false;
        char[] s1 = s.toCharArray();
        char[] t1 = t.toCharArray();
        Arrays.sort(s1);
        Arrays.sort(t1);

        return Arrays.equals(s1, t1);
    }
}

hash

public class Solution {
    public boolean isAnagram(String s, String t) {
       if(s == null || t == null)
            return false;

        if(s.length() != t.length())
            return false;
        //长度相等
        int[] alpha = new int[26];
        for(int i = 0; i < s.length(); i++){
            alpha[s.charAt(i)-'a']++;
        }

        for(int i = 0; i < t.length(); i++){
            //建立在长度相等的情况下
            //存在小于0的情况就不是异位构词
            if(--alpha[t.charAt(i)-'a'] < 0)
                return false;
        }
        return true;
    }
}

你可能感兴趣的:(异位构词)