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

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

问题描述

我想作字谜算法,但 这code不起作用。哪里是我的错吗? 例如DES和sed是字谜,但输出并不字谜 同时,我不得不使用字符串的方法。不数组。 :)

 公共静态布尔isAnagram(字符串S1,S2字符串)
{
    字符串delStr =;
    字符串中newstr =;

    的for(int i = 0; I< s1.length();我++)
    {
        对于(INT J = 0; J< s2.length(); J ++)
        {
            如果(s1.charAt(I)== s2.charAt(J))
            {
                delStr = s1.substring(I,I + 1);
                中newstr = s2.replace(delStr,);
            }
        }
    }

    如果(newStr.equals())
        返回true;
    其他
        返回false;
}
 

解决方案

这是更简单的方法可能是在两个字符串中的字符,只是排序,并比较它们是否相等:

 公共静态布尔isAnagram(字符串S1,S2字符串){

        //提前终止检查,如果字符串的长度不等,
        //然后它们不能字谜
        如果(s1.length()!= s2.length()){
            返回false;
        }
        S1 = s1.toLowerCase();
        S2 = s2.toLowerCase();
        的char [] C1 = s1.toCharArray();
        的char [] C2 = s2.toCharArray();
        Arrays.sort(C1);
        Arrays.sort(C2);
        字符串SC1 =新的String(C1);
        字符串SC2 =新的String(C2);
        返回sc1.equals(SC2);
}
 

我个人认为这是更具可读性比嵌套的for循环= P

这有为O(n log n)的运行时的复杂性,其中 N 越长字符串的长度。

编辑:这不是最佳的解决方案。见@ aam1r的答案最有效的方法(例如,你其实应该说,在接受记者采访什么的)

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);
}

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

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

Edit: 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天全站免登陆