黑马程序员技术交流社区

标题: 【已解决】个人写的求回文字符串的代码,大家帮忙看看... [打印本页]

作者: hello world    时间: 2012-8-6 19:54
标题: 【已解决】个人写的求回文字符串的代码,大家帮忙看看...
本帖最后由 刘向阳 于 2012-8-7 18:58 编辑

public class HW
{
    public static void main(String[] args)
    {
        if(isHW(""))
        {
                System.out.println("yes");
        }
        else
        {
                System.out.println("no");
        }
    }
    public static boolean isHW(String str)
    {   
        int low=0;
        int high=str.length()-1;
        while(low<high)
        {
            if(str.charAt(low++)!=str.charAt(high--))
            {
                return false;        
            }
        }
        return true;
    }
}
作者: 李勇    时间: 2012-8-6 21:37
本帖最后由 李勇 于 2012-8-6 21:39 编辑

你没有在 函数里传递参数进去  if无法比对 String stc 的长度  

    if(isHW(""))  这里传入 关键的参数才能运行

这是初手常犯的错误  多看看书和写题就可以
  1. public class WH{
  2. public static void main(String[] args)
  3. {
  4. if(isHW("111"))
  5. {
  6. System.out.println("yes");
  7. }
  8. else
  9. {
  10. System.out.println("no");
  11. }
  12. }
  13. public static boolean isHW(String str)
  14. {
  15. int low=0;
  16. int high=str.length()-1;
  17. while(low<high)
  18. {
  19. if(str.charAt(low++)!=str.charAt(high--))
  20. {
  21. return false;
  22. }
  23. }
  24. return true;
  25. }
  26. }

  27. 运行结果:

  28. yes
复制代码

作者: 叶征东    时间: 2012-8-6 21:54
本帖最后由 叶征东 于 2012-8-7 16:59 编辑

不好意思,错了。静闭自省去。

作者: 李知伦    时间: 2012-8-7 03:55
我暂时还没发现1L的错误.....

我发现2L:1L很明显只写了空字符,没写读取等语句,你随便加个想判断的字符不就ok了,例如12321,abcdcba,awgafasef

我发现3L:
1.你改完编译了吗,return null; 给返回值为boolean的方法? 明显编译都过不去
2.先不说编译过不过,你的算法是:当字符串左右两段字符相等,就返回ture,后面的没机会判断了...显然不对

作者: 杨震    时间: 2012-8-7 10:13
楼上解释很清楚了,楼主回文函数没有问题,3L解法错误
作者: 焦晨光    时间: 2012-8-7 10:24
楼主,你要自信,你的代码没有问题!
作者: 刘渝灵    时间: 2012-8-7 18:23
没问题,是我的话会在函数里面加个判断。
if(str==null||str.equals(""))
       return false;




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2