回文串,回文数,最长回文子串


一. 回文串

判断输入的字符串是否为回文串
Input : a s d f d s a
return : true

解题思路:

在此处我想到的是快排的思想:

  • 定义两个标兵,让后让 leftright 从字符串两端向中心遍历
  • 如果leftright指向的字符不相等返回false,当left==right时为回文串
public class HuiwenString {

    public static boolean isPalindromeString(String str) {
        int left = 0;
        int right = str.length() - 1;
        if(str.length() == 0 || str == null) {
            return false;
        }
        while(left <= right) {
            if( str.charAt(left) == str.charAt(right) ) {
                left++;
                right--;
            }else {
                return false;
            }
        }
        return true;
    }
    public static void main(String[] args) {
        System.out.print("请输入字符串: ");
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        System.out.println(isPalindromeString(str));
    }
}

二. 回文数

判断输入的数是否为回文数
Input : 10001
return : 10001

解题思路

类比于上面回文串拿到每一位字符相比较,此处用第二种反转思想相对简单实现

  • 通过将要判断的数num拆分,进而得到新的x,判断num是否等于x
  • 找出区间[a,b]上所有的回文数(偶数 / 奇数 / 素数)

区间内回文数输出

public class HuiwenNumber {
    public static int isPalindrome(int x) {
        int rs = 0;  int temp = x;
        while(temp > 0) {
            rs *= 10;
            rs += temp % 10;
            temp /= 10;
        }
        if(x == rs) {
            return x;
        }else {
            return -1;
        }
    }

    public static void main(String[] args) {
        int msg = 0;
        System.out.print("请输入判断回文数的区间: ");
        Scanner input = new Scanner(System.in);
        int start = input.nextInt();
        int end = input.nextInt();
        for(int i = start; i <= end; i++) {
             // 偶数回文数
            // if(isPalindrome(i) > 0)
            if(isPalindrome(i) > 0) {
                System.out.println(isPalindrome(i));
                msg++;
            }
        }
        System.out.println("该区间回文数共有" + msg + "个!");
    }
}

三. 最长回文子串

发布了77 篇原创文章 · 获赞 118 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_43232955/article/details/103073934