且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除相邻重复字母时的 StringIndexOutOfBounds

更新时间:2023-12-05 17:59:04

当您尝试将此字符串 "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;
     }