检查回文字符串 [英] Check string for palindrome

查看:38
本文介绍了检查回文字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

palindrome 是一个单词、短语、数字或其他可以阅读的单位序列两个方向都一样.

A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction.

为了检查一个词是否是回文,我得到了这个词的字符数组并比较了字符.我测试了它,它似乎有效.但是我想知道它是否正确或者是否有需要改进的地方.

To check whether a word is a palindrome I get the char array of the word and compare the chars. I tested it and it seems to work. However I want to know if it is right or if there is something to improve.

这是我的代码:

public class Aufg1 {
    public static void main(String[] args) {
        String wort = "reliefpfpfeiller";
        char[] warray = wort.toCharArray(); 
        System.out.println(istPalindrom(warray));       
    }

    public static boolean istPalindrom(char[] wort){
        boolean palindrom = false;
        if(wort.length%2 == 0){
            for(int i = 0; i < wort.length/2-1; i++){
                if(wort[i] != wort[wort.length-i-1]){
                    return false;
                }else{
                    palindrom = true;
                }
            }
        }else{
            for(int i = 0; i < (wort.length-1)/2-1; i++){
                if(wort[i] != wort[wort.length-i-1]){
                    return false;
                }else{
                    palindrom = true;
                }
            }
        }
        return palindrom;
    }
}

推荐答案

或者,递归.

Alternatively, recursion.

对于任何正在寻找更短递归解决方案的人来说,检查给定的字符串是否满足回文:

For anybody who is looking for a shorter recursive solution, to check if a given string satisfies as a palindrome:

private boolean isPalindrome(String s) {
    int length = s.length();

    if (length < 2) // If the string only has 1 char or is empty
        return true;
    else {
        // Check opposite ends of the string for equality
        if (s.charAt(0) != s.charAt(length - 1))
            return false;
        // Function call for string with the two ends snipped off
        else
            return isPalindrome(s.substring(1, length - 1));
    }
}

<小时>

OR甚至更短,如果您愿意:

private boolean isPalindrome(String s) {
    int length = s.length();
    if (length < 2) return true;
    return s.charAt(0) != s.charAt(length - 1) ? false :
            isPalindrome(s.substring(1, length - 1));
}

这篇关于检查回文字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆