2017-02-11 98 views
3

我的代碼有一些問題,因爲我的任務中的測試用例出錯了,當我在線提交代碼時出現運行時錯誤。該測試用例可以是任何字符串。我相信代碼中的一切都很好,因爲我已經爲許多測試用例手動進行了檢查。使用遞歸來檢查字符串是迴文嗎?

這裏是代碼

public static boolean isStringPalindrome(String input) { 
    if(input.length()==0 || input.length()==1) 
     return true; 

    int first = 0; 
    int last = input.length()-1; 

    if(input.charAt(first) != input.charAt(last)) 
     return false; 

    String str=""; 
    for(int i=first+1;i<last;i++){ 
     str = str+input.charAt(i); 
    } 
    boolean sa = isStringPalindrome(str); 
    return sa; 
} 

採樣輸入

racecar 

輸出

true 

採樣輸入

pablo 

輸出

false 
+0

您正在收到運行時錯誤?我很驚訝!你能發佈你正在得到什麼確切的錯誤嗎? –

+0

@WasiAhmad在線工具並沒有告訴它它只是顯示簡單的msg'運行時錯誤(NZEC)' –

+0

我已經更新了我的答案,除了'null'字符串檢查外,我沒有在您的代碼中發現任何問題。您可以嘗試添加該條件。 –

回答

1

更簡單的方法來檢查迴文可以是:

public static boolean isPalindrome(String s) 
{ if (input == null) 
     return false; 
    else if(s.length() == 0 || s.length() == 1) 
     return true; 

    /* check for first and last char of String: 
    * if they are same then do the same thing for a substring 
    * with first and last char removed. and carry on this 
    * until you string completes or condition fails. 
    */ 
    if(s.charAt(0) == s.charAt(s.length()-1)) 
     return isPalindrome(s.substring(1, s.length()-1)); 

    return false; 
} 

更新

你得到runtime error(NZEC)這意味着non-zero exit code 。這意味着你的程序意外結束。我沒有看到任何理由,只是您的程序沒有null支票。否則,我已經仔細檢查了你的代碼,你正在做與我所建議的相同的事情。

+0

我也這樣做,但不知何故,我的代碼不能用於單個測試用例,我不知道可能是什麼情況? –

+0

你有沒有發現你的代碼不工作的任何測試用例? –

+0

不,我沒有找到任何測試用例,雖然檢查了許多不同的測試案例,並且都顯得工作正常 –

3

您的代碼似乎是遞歸測試,如果String是迴文過於複雜。類似的,

public static boolean isStringPalindrome(String input) { 
    if (input == null) { 
     return false; 
    } else if (input.isEmpty() || input.length() == 1) { 
     return true; 
    } 
    int len = input.length() - 1; 
    return input.charAt(0) == input.charAt(len) // 
      && isStringPalindrome(input.substring(1, len)); 
} 

是遞歸的,沒有嵌入for循環。因爲如果你能做到這一點,你應該這樣做

public static boolean isStringPalindrome(String input) { 
    if (input == null) { 
     return false; 
    } else if (input.isEmpty() || input.length() == 1) { 
     return true; 
    } 
    int len = input.length(); 
    for (int i = 0; i <= len/2; i++) { 
     if (input.charAt(i) != input.charAt(len - 1 - i)) { 
      return false; 
     } 
    } 
    return true; 
} 
+1

感謝您的快速幫助,但我無法找到我的代碼有什麼問題,因爲我的邏輯與您的邏輯相同。 –

+0

@PrinceVijayPratap你的代碼缺少'null',這可能是測試用例正在測試的內容。 –

+0

@JornVernee好的等待我會嘗試 –