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?

题意:给定两个字符串s和t,判断s和t是否为相同字母的异序词
例:s = "anagram", t = "nagaram", 返回 true.
s = "rat", t = "car",返回 false.
note:
假设字符串只包含小写字母
follow up:
如果字符串中含有特殊字符

思路:将字符串s和t存入字符数组中,然后将数组排序,逐个比较数组中的字符。也可用于特殊字符的处理

public boolean isAnagram(String s, String t) {
        char[] chars1 = s.toCharArray();
        char[] chars2 = t.toCharArray();
        int len1 = chars1.length;
        int len2 = chars2.length;
        if(len1 != len2)
            return false;
        Arrays.sort(chars1);
        Arrays.sort(chars2);
        for(int i = 0; i < len1; i++){
            if(chars1[i] != chars2[i])
                return false;
        }
        return true;
    }

LeetCode提供的方法更简洁。用Arrays的equals方法,直接比较两个数组是否相等。

public boolean isAnagram(String s, String t){
        if(s.length() != t.length())
            return false;
        char[] chars1 = s.toCharArray();
        char[] chars2 = t.toCharArray();
        Arrays.sort(chars1);
        Arrays.sort(chars2);
        return Arrays.equals(chars1, chars2);
    }

思路2:定义一个26个元素的数组,将s.charAt(i) - 'a'作为数组下标,遍历字符串中的字符,s中的字符让数组对应下标的元素加1,t中的字符让数组对应下标的元素减1,

然后遍历数组,如果存在不为0的元素,则返回false。

public boolean isAnagram(String s, String t){
        if(s.length() != t.length())
            return false;
        int[] num = new int[26];
        for(int i = 0; i < s.length(); i++){
            num[s.charAt(i) - 'a']++;
            num[t.charAt(i) - 'a']--;
        }
        for(int i : num){
            if(i != 0)
                return false;
        } 
        return true;
    }

改进:

public boolean isAnagram(String s, String t){
        if(s.length() != t.length())
            return false;
        int[] num = new int[26];
        for(int i = 0; i < s.length(); i++){
            num[s.charAt(i) - 'a']++;
        }
        for(int i = 0; i < t.length(); i++){
            num[t.charAt(i) - 'a']--;
            if(num[t.charAt(i) - 'a'] < 0)
                return false;
        }
        return true;
    }

 

posted @ 2018-03-15 10:02  zeroingToOne  阅读(206)  评论(0编辑  收藏  举报