JAVA - Algorithms and Data Structures
Given a string of characters formed with characters a and b. The string is marked with the middle with an X, which represents the middle of the list. Example: aabbXbaa. Write a method that indicates whether the given string is a palindrome ( reads the same from left to right and right to left), returning true if it is, and false if it is not. Use an array stack to parse the string. Write the pseudocode first, then code the method.
Algorithm Steps:
Make an empty stack S
For each element of the array until X, say from index i to k, push them to the stack S
For each element after X, do the following:
Pop an element from the stack S.
Compare it with the current element. If they are not same, then the string is not palindrome. Return
Move to the next array element
If the control is here, this means that the string is palindrome.
CODE
import java.util.Stack;
public class Main {
public static boolean isPalindrome(String s) {
Stack<Character> stack = new Stack<>();
int i = 0;
while (s.charAt(i) != 'X') {
stack.push(s.charAt(i));
i ++;
}
i ++;
while (i < s.length()) {
char popped = stack.pop();
if (popped != s.charAt(i)) {
return false;
}
i ++;
}
return true;
}
public static void main(String[] args) {
System.out.println(isPalindrome("aabbXbbaa"));
System.out.println(isPalindrome("aabbXbaa"));
}
}
JAVA - Algorithms and Data Structures Given a string of characters formed with characters a and...