Java judges whether a string is a palindrome

First of all, palindrome refers to a form similar to "12345", "abcdcba", i.e. both mindfulness and anti-mindfulness are the same string

To determine whether a string is a palindrome, here are two methods

1. Flip the string to determine whether the flipped string is equal to the original string

public static void main(String[] args) {

String s="abcdcba";

// Use StringBuilder's reverse method to reverse the string

StringBuilder sb=new StringBuilder(s);

String afterReverse=sb.reverse().toString();

//To determine whether the reversed string is equal to the original string, compareTo, equals,

int isequal=afterReverse.compareTo(s); //If equal, output 0

if (isequal==0){

System.out.println("It is a palindrome");

}else

System.out.println("Not a palindrome");

}

Note: compareTo and equals judge the string considering case, that is, case is regarded as unwilling to wait. If you need to ignore case, you can use equalsIgnoreCase

2. The for loop judges whether the corresponding characters are equal in turn

public static void main(String[] args) {

String s="12344321";

int l=s.length();

System.out.println(l/2);

int result=1;

//Compare from the middle to both sides

for (int i=0;i

if (s.charAt(i)==s.charAt(l-i-1)){

result=0;

}else{

result=1;

break; //The comparison needs to jump out of the loop when you don't want to wait, otherwise as long as the last comparison is established, result=0 will be returned

}

}

if (result==0){

System.out.println("It is a palindrome");

}else {

System.out.println("Not a palindrome");

}

}

Additional method knowledge points:

1,定义两个字符串元素指针(注意java没有指针的概念),int right=T.length()-1 ;int left=0;

2,即left从左边开始,right从右边开始,依次比较所指的字符是否相等,若相等,则将left++,right--;否则,直接返回不是回文

while(left

if(T.charAt(left)!=T.charAt(right))

return false;

left++;

right--;

}

return true;

代码:

/*

* 3:

* 回文判断

* 问题描述:回文,英文palindrome,指一个顺着读和反过来读都一样的字符串,比如madam、我爱我,

* 方法一:

* 分析:使用两个"指针"分别从字符串头和尾扫描,若每一个"指针"所指值都相等,这为回文

*/

public boolean isPalindrome(String s){

if(s==null)

return false;

int left=0;

int right=s.length()-1;

while(left

if(s.charAt(left)!=s.charAt(right))

return false;

left++;

right--;

}

return true;

}

以上就是Java判断字符串回文的代码实例的详细内容,更多关于Java判断字符串是否是回文请关注聚米学院其它相关文章!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324325737&siteId=291194637