【发布时间】:2014-03-31 06:40:50
【问题描述】:
我需要找到一个字符串中的所有回文。它需要用户输入
示例:“abbaalla”
它循环创建一个随着循环进行而改变的子字符串。
示例:检查回文“a”(真)“ab”(假)“abb”(假)“abba”(真)等等..
一旦达到单词的最大长度,它就会迭代子字符串的开头并重复
示例:检查回文“b”“bb”“bba”等..
我需要更改代码,以便一旦找到第一个最大的回文(“abba”),循环的开始将发生在该子字符串之后。所以下一个回文应该是“alla”
最终输出应该是一个包含所有回文的字符串。在这种情况下;
输出:“阿巴阿拉”
此程序当前也导致:字符串索引超出范围:-1
public static String findAllPalindromes(String input){
int indexStart = 0;
int wordMax = input.length();
int wordLength;
String checkPalindrome;
String allPalindromes = "";
for (wordLength = 2; wordLength <= wordMax; wordLength++) {
//creates a substring to check against isAllPalindrome method
checkPalindrome = input.substring(indexStart, wordLength);
//checks checkPalindrome string to see if it is a palindrome
if (isAllPalindrome(checkPalindrome) == true){
allPalindromes += " " + checkPalindrome;
if (checkPalindrome.length() >= allPalindromes.length()){
allPalindromes = checkPalindrome;
}
}
//once program reads string through once, increment index and scan text again
if (wordLength == wordMax && indexStart < wordMax){
indexStart++;
wordLength = 0;
}
}
System.out.println("The palindromes in the text are: ");
System.out.println(allPalindromes);
return allPalindromes;
}
【问题讨论】:
-
我们在为你做功课吗?
-
这是一个家庭作业,我已经做了很多尝试来解决这个问题。寻求友好社区的帮助
标签: java loops palindrome