删除相邻重复字母时的 StringIndexOutOfBounds [英] StringIndexOutOfBounds when removing adjacent duplicate letters

查看:42
本文介绍了删除相邻重复字母时的 StringIndexOutOfBounds的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

 public static String removeAdjDuplicates(String s) {
     if(s == "" || s == null || s.isEmpty())
         return s;

     if(s.length() < 2) 
         return s;

     if(s.charAt(0) != s.charAt(1))
          s = s.charAt(0) + removeAdjDuplicates(s.substring(1));

     if(s.charAt(0) == s.charAt(1)) //line 37
         return removeAdjDuplicates(s.substring(2));

     return s;
 }

输入字符串ull"时,出现以下错误:

With the input string "ull", I get the following error:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
    at java.lang.String.charAt(String.java:658)
    at GFG.removeAdjDuplicates(File.java:37)
    at GFG.main(File.java:16)

我阅读并尝试了类似问题的答案,但我不确定哪里出了问题.

I read and tried answers given to similar questions, but I'm not sure what is wrong.

推荐答案

当您尝试将此字符串 "ull" 传递给方法时,该字符串中的最后一个字母应为字母u"因为你用这个

As you Try to pass this string "ull" to the method the last letter in the String should be the letter "u" because you use this

if(s.charAt(0) != s.charAt(1))
          s = s.charAt(0) + removeAdjDuplicates(s.substring(1));

因为你不像方法中的其他条件那样返回字符串,它会继续到第 37 行的下一个条件并且你只有一个字母,而条件检查第一个和第二个字符......没有第二个字母所以你得到这个错误..所以解决方案是像这样返回 s

as you dont return the String back like the other conditions in the method it will continue to the next condition at line 37 and u have only one letter while the condition checking the first and the second characters ... there is no second letter so you get this error .. so the solution is to return s like this

if(s.charAt(0) != s.charAt(1)){
          s = s.charAt(0) + removeAdjDuplicates(s.substring(1));
         return s;
     }

这篇关于删除相邻重复字母时的 StringIndexOutOfBounds的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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