java利用栈判断回文
时间: 2023-12-05 16:55:11 浏览: 82
探讨一百一十一
判断回文可以利用栈的后进先出特性,将原字符串中的每个字符依次入栈,然后再依次出栈与原字符串进行比较,如果全部相等则为回文,否则不是回文。
以下是Java代码实现:
```java
import java.util.Stack;
public class Palindrome {
public static boolean isPalindrome(String s) {
Stack<Character> stack = new Stack<>();
int len = s.length();
for (int i = 0; i < len; i++) {
stack.push(s.charAt(i));
}
for (int i = 0; i < len; i++) {
if (stack.pop() != s.charAt(i)) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String s1 = "racecar";
String s2 = "hello";
System.out.println(s1 + " is palindrome? " + isPalindrome(s1));
System.out.println(s2 + " is palindrome? " + isPalindrome(s2));
}
}
```
输出结果:
```
racecar is palindrome? true
hello is palindrome? false
```
阅读全文