`
sunzhiqiang1984
  • 浏览: 126067 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类

判断字符串是回串(回文字符串)

阅读更多

    面试一家公司时被问到的,回文字符串,类似“abcdcba”,当时那家公司让我用迭代方法做,我一下子晕了,好像应该用递归吧?当时把这两个概念搞混了,只是说出了自己递归的思路。其实应该是用递归来做。下面给出代码:

public class Palindrome {

	public static void main(String[] args) {
		String tempString = "abcwbwwcba";
		boolean test = isPalindrome(tempString);
		System.out.print(test);
	}
	
	public static boolean isPalindrome(String testString)
	{
		if(testString == null)
		{
			return false;
		}
		
		if(testString.length() == 0 || testString.length() == 1)
		{
			return true;
		}
		
		String firstString = testString.substring(0,1);
		String lastString = testString.substring(testString.length() -1,testString.length());
		if(firstString.equals(lastString))
		{
			return isPalindrome(testString.substring(1,testString.length()-1));
		}
		else 
		{
			return false;
		}
	}
}

 

分享到:
评论
1 楼 兰博基尼 2010-09-12  
迭代不就是循环么...来个for循环就O了吧,你试试这个...
public class Palindrome{
    public boolean isPalindrome(String[] str) {
         int len = str.length;
boolean b = false;
for(int i = 0; i <= len/2; i++ ) {
            if(str[i] != str[len-i-1]) {
                break;
            } else {
                b = true;
            }
            
         }
return b;
    }
   
    public static void main(String[] args) {
         String[] str = {"L","V","E","V","L"};
        
         if(new Palindrome().isPalindrome(str) ) {
                System.out.println("该字符串是回文字符串!");
         } else {
                System.out.println("该字符串不是回文字符串!");
           }
            
     }
}

相关推荐

Global site tag (gtag.js) - Google Analytics