检测回文串

对于一个字符串,如果从前向后读和从后向前读都是同一个字符串,则称之为回文串。


一种解决方案是:先判断该字符串的第一个字符和最后一个字符是否相等。如果相等,检查第二个字符和倒数第二个字符是否相等。这个过程持续进行,直到出现不匹配的情况或者串中所有的字符都检查完毕,当字符串有奇数个字符时,不用检查中间字符。


package com.dx.ex;


import java.util.Scanner;


public class CheckPalindrome {
public static void main(String[] args) {
// Create a scanner
Scanner input = new Scanner(System.in);


// prompt the user to enter a string
System.out.println("Enter a string:");
String s = input.nextLine();


if (isPalindrome(s)) {
System.out.println(s + " is a palindrome");
} else {
System.out.println(s + " is not a palindrome");
}
}


/** Check if a string is a palindrome */
public static boolean isPalindrome(String s) {
// The index of the first character in the string
int low = 0;


// The index of the last character in the string
int high = s.length() - 1;


while (low < high) {
if (s.charAt(low) != s.charAt(high)) {
return false;// Not a palindrome
}


low++;
high--;
}


return true;// The string is a palindrome
}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值