문자열에서 가장 긴 구문을 찾는 간단한 프로그램을 작성하고 있습니다. 내가하는 일은 각 부분 문자열이 회문이고 그 길이를 검사하는 것입니다. 길이가 이전 길이보다 길면 새로운 가장 긴 하위 문자열이 있습니다. 예를 들어 "babad"는 "bab"또는 "aba"를 반환합니다. 하지만 내 문제는 인덱스가 하위 문자열 호출에서 벗어나서 그 이유를 파악할 수 없다는 것입니다.하위 문자열 인덱스가 범위를 벗어났습니다.
public class LongestPal{
public static void main(String[] args)
{
String test = new String("babad");
String result = longestPalindrome(test);
}
public static String longestPalindrome(String s) {
int length = 0;
String answer = new String();
for(int i = 0;i<=s.length();i++)
{
for(int j = 0; j<= s.length();j++)
{
String subStr = s.substring(i,j); // Get all substrings
System.out.println(subStr); // Checking to see if all are printed
boolean result = isPalindrome(subStr); //Check for palindrome
if(result)
{
if(length < subStr.length()) //If length of new substr is greater than the old one,
//the new answer will be longer substring
{
answer = subStr;
}
}
}
}
return answer;
}
public static boolean isPalindrome(String s) //Recursive palindrome checker
{
if(s.length() == 0 || s.length() == 1)
return true;
if(s.charAt(0) == s.charAt(s.length()-1))
return isPalindrome(s.substring(1, s.length()-1));
return false;
}
}
나는 "babbad"가 오류가 발생할 때까지 모든 하위 문자열 조합을 얻습니다.
* "예를 들어"babbad "는"bab "또는"aba "중 하나를 반환합니다."* ... aba? – Tom
@ 톰 아마 OP가 _abba _... 오타를 말하고 싶었 을까요? – rafid059
'j Jyr