Java实现回文串判断的方法
回文串是什么?
- “回文串”是一个正读和反读都一样的字符串,初始化标志flag=true,比如“上海自来水来自海上”或者“sos”等等就是回文串。
回文串判断方法实现
- (1)字符串反转法
public boolean isPalindrome(){
String str = "上海自来水来自海上";
StringBuilder sb = new StringBuilder();
sb.reverse(); //将字符串进行反转
String newStr = new String(sb);
if (str.equals(newStr)) { //判断反转后的字符串和之前的字符串是否相等
return true;
} else {
return false;
}
}
- (2) 双指针法
public void isPalindrome(){
String str = "上海自来水来自海上";
int i, j;
for (i = 0, j =text.length() - 1; i <= j ; i++,j--) {
if (text.charAt(i) == text.charAt(j)){
return true;
}else {
return false;
}
}return true;
}
- (3) 利用栈操作法
private void isPalindrome() {
//1.获取用户的输入 字符串
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a text:");
String text = scanner.nextLine();
//2.创建一个栈 字符数据
ArrayStack<Character> stack = new ArrayStack<>();
//3.遍历字符串 并做出栈和入栈的操作
char c;
for (int i = 0; i < text.length(); i++) {
//当前text的长度是否是奇数
if(text.length() % 2 == 1 || i == text.length() / 2){
continue;
}
c = text.charAt(i);
if (stack.isEmpty()){
stack.push(c); //如果栈为空 直接进
}else{
if (c != stack.peek()){ //看栈顶是否和当前字符c相等
stack.push(c); //不相等 直接进
}else{
stack.pop(); //相等 相消 直接弹栈
}
}
}
//如果栈为空 则回文; 否则不回文
if (stack.isEmpty()){
System.out.println(text + " is a palindrome");;
}else {
System.out.println(text + " is not a palindrome");
}
}