LeetCode——第242题:有效的字母异位词

题目:

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。

示例 1:

输入: s = “anagram”, t = “nagaram”
输出: true

示例 2:

输入: s = “rat”, t = “car”
输出: false

说明:

你可以假设字符串只包含小写字母。

进阶:

如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

思考:感觉用个二维数组,第一列保存字符,第二行保存出现次数?

代码:

package leetCode;


/**
 * 时间:3ms
 * 2018.7.22
 * 有效字母异位词
 * 思路:对于两个字符串他们的字符相同,并且相同字符的个数相同,因此可以保存这些字符和他们的次数
 * 然后比较,这里用一个int【】数组保存他们的次数,并且长度为26对应26个字母。
 * @author dhc
 *
 */
public class TwoHundredsAndFortyTwo {
    public static boolean isAnagram(String s, String t) {
        //这一步是简单判断一下,感觉可以稍微提高一下速度?
        if(s.length() != t.length()) {
            return false;
        }
        int[] tem = new int[26];
        char[] sc = s.toCharArray();
        for (int i = 0; i < sc.length; i++) {
            tem[sc[i]-'a']++;
        }
        char[] tc = t.toCharArray();
        for(int i = 0; i < tc.length;i++) {
            tem[tc[i]-'a']--;
        }
        int index = 0;
        for(int i = 0;i < tem.length;i++) {
            index = i;
            if(tem[i] != 0) {
                break;
            }
        }
        if(index == 25) {
            return true;
        }else {
            return false;
        }
    }
    public static void main(String[] args) {
        String a = "asdaaa";
        String b = "asdasd";
        System.out.println(isAnagram(a,b));
    }
}

猜你喜欢

转载自blog.csdn.net/rbreeze/article/details/81156651