用于确定字符串是否为回文的java堆栈
我发现在Stack stack = new Stack(str.length());
上找不到符号错误
为什么这不起作用
import java.util.Scanner;
/*/
This progrma will read string and return if the string is
palindrome word, phrase, sentence or not. if the word is not palindrome
the progrma will pritn out false otherwise the progrma will print out true.
*/
public class PalindromeDemo
{
public static boolean isPalindrome(String str)
{
boolean isPal = true;
//creating stack
Stack stack = new Stack(str.length());
//push all character into stack
for(int i=0; i<str.length(); i++)
{
stack.push(str.charAt(i));
}
// now traverse str and check current character with top of stack
for(int i=0; i<str.length(); i++)
{
char c = (char) stack.pop();
// if not equal, break
if(Character.toLowerCase(c) != Character.toLowerCase(str.charAt(i)))
{
isPal = false;
break;
}
}
return isPal;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String str;
System.out.println("Enter a string: ");
str = sc.nextLine();
System.out.println(isPalindrome(str));
}
}
# 1 楼答案
似乎您忘记了
Stack
的导入语句:然后会出现另一个错误,因为
Stack
只有一个无参数构造函数,它不能像代码中那样接受int
参数。解决方法是简单地删除参数:除此之外,除了一些不好的做法外,你的程序似乎还在运行:
Stack
,Stack<Character>
会更好Stack
,您应该使用Deque
和ArrayDeque
i
-th和第str.length() - i - 1
-th个字母时,堆栈对于这项任务来说真的是太浪费了,占用了太多额外的存储空间