Question

JAVA - Algorithms and Data Structures Given a string of characters formed with characters a and...

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.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Algorithm Steps:

  1. Make an empty stack S

  2. For each element of the array until X, say from index i to k, push them to the stack S

  3. 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

  4. 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"));

}

}

Add a comment
Know the answer?
Add Answer to:
JAVA - Algorithms and Data Structures Given a string of characters formed with characters a and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT