java中的字谜算法 [英] Anagram algorithm in java

查看:21
本文介绍了java中的字谜算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做字谜算法,但是此代码不起作用.我的错在哪里?例如 des 和 sed 是 anagram 但输出不是 anagram同时我必须使用字符串方法.不是数组.:)

I would like to make anagram algorithm but This code doesn't work. Where is my fault ? For example des and sed is anagram but output is not anagram Meanwhile I have to use string method. not array. :)

public static boolean isAnagram(String s1 , String s2)
{
    String delStr="";
    String newStr="";

    for(int i=0;i<s1.length();i++)
    {
        for(int j=0 ; j < s2.length() ; j++)
        {
            if(s1.charAt(i)==s2.charAt(j))
            {
                delStr=s1.substring(i,i+1);
                newStr=s2.replace(delStr,"");
            }
        }           
    }

    if(newStr.equals(""))
        return true;
    else
        return false;
}

推荐答案

一种更简单的方法可能是对两个字符串中的字符进行排序,然后比较它们是否相等:

An easier way might be to just sort the chars in both strings, and compare whether they are equal:

public static boolean isAnagram(String s1, String s2){

        // Early termination check, if strings are of unequal lengths,
        // then they cannot be anagrams
        if ( s1.length() != s2.length() ) {
            return false;
        }
        s1=s1.toLowerCase();
        s2=s2.toLowerCase();
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        Arrays.sort(c1);
        Arrays.sort(c2);
        String sc1 = new String(c1);
        String sc2 = new String(c2);
        return sc1.equals(sc2);
}

我个人认为它比嵌套的 for-loops =p 更具可读性

Personally I think it's more readable than nested for-loops =p

这具有 O(n log n) 运行时复杂度,其中 n 是较长字符串的长度.

This has O(n log n) run-time complexity, where n is the length of the longer string.

这不是最佳解决方案.请参阅@aam1r 的答案以了解最有效的方法(即您在面试中实际应该说的话)

this is not the optimal solution. See @aam1r's answer for the most efficient approach (i.e. what you should actually say in an interview)

这篇关于java中的字谜算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆