完全披露:这是针对作业的,所以请不要发布实际的代码解决方案!
我有一个赋值,要求我从用户那里取一个字符串并将其传递给一个堆栈和一个队列,然后使用这两个来比较这些字符以确定该字符串是否为回文。我编写了程序,但似乎在某处出现了一些逻辑错误。这是相关的代码:
public static void main(String[] args) {
UserInterface ui = new UserInterface();
Stack stack = new Stack();
Queue queue = new Queue();
String cleaned = new String();
boolean palindrome = true;
ui.setString("Please give me a palindrome.");
cleaned = ui.cleanString(ui.getString());
for (int i = 0; i < cleaned.length(); ++i) {
stack.push(cleaned.charAt(i));
queue.enqueue(cleaned.charAt(i));
}
while (!stack.isEmpty() && !queue.isEmpty()) {
if (stack.pop() != queue.dequeue()) {
palindrome = false;
}
}
if (palindrome) {
System.out.printf("%s is a palindrome!", ui.getString());
} else
System.out.printf("%s is not a palindrome :(", ui.getString());
stack.dump();
queue.clear();
}
public class Stack {
public void push(char c) {
c = Character.toUpperCase(c);
Node oldNode = header;
header = new Node();
header.setData(c);
header.setNext(oldNode);
}
public char pop() {
Node temp = new Node();
char data;
if (isEmpty()) {
System.out.printf("Stack Underflow (pop)\n");
System.exit(0);
}
temp = header;
data = temp.getData();
header = header.getNext();
return data;
}
}
public class Queue {
public void enqueue(char c) {
c = Character.toUpperCase(c);
Node n = last;
last = new Node();
last.setData(c);
last.setNext(null);
if (isEmpty()) {
first = last;
} else n.setNext(last);
}
public char dequeue() {
char data;
data = first.getData();
first = first.getNext();
return data;
}
}
public String cleanString(String s) {
return s.replaceAll("[^A-Za-z0-9]", "");
}
基本上,当我在Eclipse中通过调试器运行我的代码时,我的pop和dequeue方法似乎只选择某些字母数字。我正在使用replaceAll("[^A-Za-z0-9]", "")
来“清理”用户的任何非字母数字字符串(!,?,&amp;等)。当我说它只选择某些字符时,似乎没有任何我能辨别的模式。有什么想法吗?
答案 0 :(得分:0)
假设您的队列和堆栈正确(我使用jdk中的Deque实现尝试了这一点),您的通用算法可以正常工作。由于你的任务涉及数据结构,我几乎只是采用了你的主逻辑并用ArrayDequeue替换了数据结构,所以我不觉得我正在为你回答这个问题。
String word = "ooffoo";
word = word.replaceAll("[^A-Za-z0-9]", "");
Deque<Character> stack = new ArrayDeque<Character>(word.length());
Deque<Character> queue = new ArrayDeque<Character>(word.length());
for (char c : word.toCharArray()) {
stack.push(c);
queue.add(c);
}
boolean pal = true;
while (! stack.isEmpty() && pal == true) {
if (! stack.pop().equals(queue.remove())) {
pal = false;
}
}
System.out.println(pal);
答案 1 :(得分:0)
我建议使用调试器来查看正在比较的内容,或者至少吐出一些打印行:
while (!stack.isEmpty() && !queue.isEmpty()) {
Character sc = stack.pop();
Character qc = queue.dequeue();
System.out.println(sc + ":" + qc);
if (sc != qc) {
palindrome = false;
}
}