我需要检查文本是否是回文,通过堆栈的概念,我有一个创建堆栈的函数,另一个将检查它是否是堆积该单词并将其拆散的回文。
问题在于我不知道如何进行此验证。
我的代码:
resolve
但是这段代码不起作用,因为在输入时它表示堆栈中没有对象,并且它们最终没有被插入,所以我可以取消堆栈。我怎样才能做到这一点?
PS:我是JavaScript的新手,所以代码可能是一个混乱的东西,对不起。
答案 0 :(得分:1)
你其实很亲密。您只需将连接弹出的字母组合在一起,然后与text1
(您已经这样做)进行比较。
你的第二个do while
中也有一个错误,当你应该使用你的i
变量并递减它时,你使用相同的迭代器t
作为第一个循环。以下是您的固定代码
function FILO() {
this.stack = new Array();
this.Push = function(obj) {
this.stack[this.stack.length] = obj;
}
this.Pop = function() {
if (this.stack.length > 0) {
var obj = this.stack[this.stack.length - 1];
this.stack.splice(this.stack.length - 1, 1);
return obj;
} else {
alert("Theres no objects in the stack");
}
}
}
function palindrome() {
var mystack = new FILO();
var text1;
var text2 = "";
var i;
var t;
text1 = prompt("Type a text: ");
i = text1.length;
t = text1.length;
do {
mystack.Push(text1.substr(t - i, 1));
i--;
} while (i > 0);
do {
text2 += mystack.Pop(); //Here this should be += instead of =
t--
document.write(text2, "</br>");
} while (t > 0); //use and decrement t variable in this do while
if (text1 === text2) {
alert("It is a palindrome");
} else {
alert("It's not a palindrome");
}
}
&#13;
<html>
<head>
</head>
<body>
<h1>Verification of Palindrome </h1>
<p>Press the button to see if a word is a palindrome or not</p>
<form>
<input type="button" onClick="palindrome()" value="Verifiy">
</form>
</body>
</html>
&#13;
答案 1 :(得分:0)
试试这个:
var stack1 = [], stack2 = [];
var text1 = prompt('Type a text: ');
for(var i = 0, max = text1.length; i < max; i++) {
stack1.push(text1[i]);
stack2.push(text1[max - 1 - i]);
}
var isPalindrome = true;
while(stack1.length > 0) {
if(stack1.pop() != stack2.pop()) {
isPalindrome = false;
break;
}
}
console.log('isPalindrome: ', isPalindrome);