有效的字母异位词,三个版本

一、通过类似冒号排序的形式,将两个String转成char[],通过第一个String对比将第二个String进行排序,排成跟第一个String一样。

public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) return false;
    char[] str_s = s.toCharArray();
    char[] str_t = t.toCharArray();
    char temp;
    boolean check = false;
    for (int i = 0; i < str_s.length; i++) {
        for (int j = i; j < str_t.length; j++) {
            if (str_s[i] == str_t[j]) {
                temp = str_t[i];
                str_t[i] = str_t[j];
                str_t[j] = temp;
                check = true;
                break;
            }
        }
        if (!check) return check;
        check = false;
    }
    return true;
}

二、通過Arrrays的sort方法,对两个String进行排序,再进行对比

 public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())return false;
        char[] str_s = s.toCharArray();
        char[] str_t = t.toCharArray();
        Arrays.sort(str_s);
        Arrays.sort(str_t);
        String m =new String(str_s);
        String n =new String(str_t);
        if(m.equals(n)){
            return true;
        }else return false;
    }

三、这是我觉得最巧妙的方法。

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

这三种中第二种的速度是最快的,虽然第三种最符合题意,最巧妙,但是他比第二种多做了一次循环,当处理字符串长度越长时,二者的差距就越明显。

题目来源:https://leetcode-cn.com

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值