first, the use of stacks
functionStack () { This. DataStore = []; This. top = 0;//the value of top is equal to the number of elements in the array This. Push =push; This. Pop =Pop; } functionpush (Element) { This. datastore[ This. top++] =element; } functionpop () {return This. datastore[-- This. Top]; } functionIspalindrome (word) {vars =NewStack ();//creates a new stack so that the elements in the array are pressed into the stack for(vari = 0; i < word.length; ++i) {s.push (word[i]); } varRWord = ""; while(S.top > 0) {RWord+ = S.pop ();//flips the elements in the new stack through the Pop () method } if(Word = =RWord) { return true; } Else { return false; } } varWord = "Hello"; if(Ispalindrome (Word)) {alert (Word+ "is a palindrome."); } Else{alert (Word+ "is not a palindrome."); } Word= "Racecar"; if(Ispalindrome (Word)) {alert (Word+ "is a palindrome."); } Else{alert (Word+ "is not a palindrome."); }
second, indirect use of the reverse () method of the array
functionIspalindrome (word) {varA = Word.split ("");//Convert the string to an array, split () "" is necessary varb = A.join ();//Convert an array to a string varA1 =A.reverse (); varB1 =A1.join (); if(b = = B1) {//string can use "= =", array can not return true; } Else { return false; } } varWord = "Hello"; if(Ispalindrome (Word)) {alert (Word+ "is a palindrome."); } Else{alert (Word+ "is not a palindrome."); } Word= "Racecar"; if(Ispalindrome (Word)) {alert (Word+ "is a palindrome."); } Else{alert (Word+ "is not a palindrome."); }
Determine if a string is a palindrome: use stack &reverse ()