降低isPalindrome解决方案的复杂性? [英] Decrease the complexity of isPalindrome solution?

查看:81
本文介绍了降低isPalindrome解决方案的复杂性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的isPalindrome方法

Here is my isPalindrome method

public static boolean isPalindrome(String s){
    for(int i = 0; i < s.length()/2; i++){
        int j = s.length() - 1 - i;
        if(s.charAt(i) != s.charAt(j))
            return false;
    }
    return true;
}

我的老师说我可以降低复杂性,但是我不知道如何去做.我已经只遍历了字符串的一半.有什么方法可以降低此解决方案的复杂性?

my teacher says I can decrease the complexity, but I can't see how. I already am only going through half of the string. Is there any way to decrease the complexity of this solution?

推荐答案

您可以尝试以下方法:

public static boolean isPalindrome (String str) {
    int left = 0;
    int right = str.length() - 1;

    while (left < right) {
        if (str.charAt(left) != str.charAt(right))
            return false;
        left++;
        right--;
    }
    return true;
}

这样做的优点是不必每次通过循环都计算右手索引,特别是因为它每次都必须访问字符串长度(常量).

This has the advantage of not calculating the right hand index each time through the loop, especially since it has to access the string length each time (which is constant).

顺便说一句,与sij相比,我也倾向于更有意义的变量名-我的基本规则是,如果您必须诉诸j,最好以更具表现力的方式命名您的柜台(i可以,如果它是唯一的柜台就可以).

As an aside, I also tend to prefer more meaningful variable names than s, i and j - my basic rule is that, if you have to resort to j at all, you're better off naming your counters more expressively (i is okay if it's the only counter).

这篇关于降低isPalindrome解决方案的复杂性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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