2015-01-17 3 views
1

간단한 함수를 사용하여 문자열이 회문인지 확인하고 있습니다. 그러나이 프로그램은 무한 루프로 진행됩니다.문자열이 Java에서 회문문인지 검사

public static boolean checkPalindrome(String s){ 

     boolean check = true; 
     int mid = s.length()/2; 
     int j = s.length() -1; 
     int i = 0; 
     if (s.length()%2 == 0) { 
      while(i <= mid){ 
       if (s.charAt(i) != s.charAt(j)){ 
        check = false; 
        j--; 
        i++; 
       } 
      } 
     }else if(s.length()%2 != 0){ 
      while(i < mid +1){ 
       if (s.charAt(i) == s.charAt(j)){ 
        check = false; 
        j--; 
        i++; 
       } 
      } 
     } 
     return check; 

    } 
+1

당신은 i''에 포함되지 않습니다을 yor는 조건이 거짓''경우 경우! – Jens

답변

-2

필요가 없습니다 그런 어려운 루프를 수행 할 수 있습니다. 당신은 조건 경우 내부에서 i와 j의 감소의 증가를 이동해야

boolean isPalindrome(String s) { 
    for (int i = 0; i < s.length()/2; i++) { 
     if (s.charAt(i) != s.charAt(s.length() - i - 1)) return false; 
    } 

    return true; 
} 
1

은 왜 그냥 수행 또는

String rev = new StringBuilder(s).reverse().toString(); 
return rev.equals(s); 

:

int len = s.length(); 
for (int i = 0; i < len; i++) 
    if (s.charAt(i) != s.charAt(len - i - 1)) return false; 
return true; 
+0

매우 웅변! '.ToUpper()'변환을 고려할 수도 있습니다. – Thomas

+6

이것이 사실이지만, 이는 OP가 자신의 실수를 이해하는 데 도움이되지 않습니다. 나는 당신이 그의 * actual * 문제로 그를 도울 수 있고 대체 해결책을 제안 할 수 있다면 더 선호한다. – Maroun

+2

@MarounMaroun 나는 귀하의 요점을 이해하지만,보십시오 : [XY 문제는 무엇입니까] (http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). OP가이 문제를 해결하기 위해 부적절한 방법을 사용하고 있습니다. 숙제 문제는 "while 회 돌이를 사용하여 회문 테스트"(및 명시되지 않았 음)였습니다. –

4

그것은 무한 루프에 들어 가지 않습니다 : 이런 식으로 뭔가 작동합니다.

+2

이것이 실제 답변입니다. –

+0

참으로.이 대답에서 OP는 그가 잘못한 것을 이해할 것입니다. – Maroun

+0

이 답변은 제한된 범위에서 올 바릅니다. 제 생각에는 (그리고 그것은 단지 의견 일뿐입니다) OP의 진정한 실수는 회문 테스트를하기에 부적절한 해결책을 사용하는 것이 었습니다. while 루프를 수정함으로써 OP는 가장 간단한 해결책을 찾음으로써 문제를 올바르게 해결하는 방법을 이해하지 못했습니다. –

0

다음 코드를보십시오 :

public class Palindrome { 
private static Scanner input; 

public static void main(String args[]) { 
    System.out.print("Enter a string:"); 
    input = new Scanner(System.in); 
    String str = input.nextLine(); 

    System.out.println(palindromeLoop(str)); 
    System.out.println(palindromeCheck(str)); 
    System.out.println(palindromeRecursion(str)); 
} 

// Using StringBuffer 
public static String palindromeCheck(String str) { 
    StringBuffer strName = new StringBuffer(str); 
    strName.reverse(); 

    if (strName.toString().equals(str)) { 
     return "The String is a Palindrome"; 
    } else { 
     return "Not a Palindrome!!!"; 
    } 
} 

// Using For-Loop 
public static String palindromeLoop(String str) { 
    String original = str; 
    String reverse = ""; 

    for (int i = str.length() - 1; i >= 0; i--) { 
     reverse = reverse + original.charAt(i); 
    } 

    if (original.equals(reverse)) { 
     return "The String is a Palindrome"; 
    } else { 
     return "Not a Palindrome!!!"; 
    } 
} 

// Using Recursion 
public static String palindromeRecursion(String str) { 
    if (str.length() <= 1) { 
     return "The String is a Palindrome"; 
    } else if (str.charAt(0) != str.charAt(str.length() - 1)) // Base case 
     return "Not a Palindrome!!!"; 
    else 
     return palindromeRecursion(str.substring(1, str.length() - 1)); 
} 
0
class CheckPalindrome { 
    boolean isPalindrome(String text) { 
     int i = 0; 
     int j = text.length() - 1; 
     while (i < j) { 
      while (!Character.isLetter(text.charAt(i)) && i < j) { 
       ++i; 
      } 
      while (!Character.isLetter(text.charAt(j)) && i < j) { 
       --j; 
      } 
      if (Character.toLowerCase(text.charAt(i++)) != Character.toLowerCase(text.charAt(j--))) { 
       return false; 
      } 
     } 
     return true; 
    } 
} 




@Test 
    public void isPalindrome() throws Exception { 

     CheckPalindrome checkPalindrome = new CheckPalindrome(); 
     String text = "No, it is opposition"; 
     assertTrue(checkPalindrome.isPalindrome(text)); 

    } 
관련 문제