[22 / 5 / ?]
package teststackofpalindromes;
public class StackOfPalindromes {
static final int DEFAULT_CAPACITY = 5;
int size;
String words[];
boolean isEmpty() {
return (size < 0);
}
// A no-arg constructor that invokes an arg-constructor, which creates a stack with the specified capacity.
StackOfPalindromes() {
this(DEFAULT_CAPACITY);
}
StackOfPalindromes(int DEFAULT_CAPACITY) {
words = new String[DEFAULT_CAPACITY]; // Maximum size of StackOfPalindromes
size = -1;
}
// A method named push() that takes a word, filters it from any non-alphabetic characters (i.e. remove numbers and other symbols), checks if it is a palindrome, and pushes it to the stack only if its palindrome.
void push(String str) {
if (isPalindrom(str)) {
words[++size] = str;
}
}
boolean isPalindrom(String str) {
// filters it from any non-alphabetic characters (i.e. remove numbers and other symbols)
str = str.replaceAll("[^a-zA-Z]", "");
// checks if it is a palindrom
return new StringBuilder(str).reverse().toString().equals(str);
}
// A method named pop() that returns the word on top of the stack and removes it from the stack.
String pop() {
String str = words[size--];
return str;
}
}
That's stackOfPalindromes class
public class StackOfPalindromes {
static final int DEFAULT_CAPACITY = 5;
int size;
String words[];
boolean isEmpty() {
return (size < 0);
}
// A no-arg constructor that invokes an arg-constructor, which creates a stack with the specified capacity.
StackOfPalindromes() {
this(DEFAULT_CAPACITY);
}
StackOfPalindromes(int DEFAULT_CAPACITY) {
words = new String[DEFAULT_CAPACITY]; // Maximum size of StackOfPalindromes
size = -1;
}
// A method named push() that takes a word, filters it from any non-alphabetic characters (i.e. remove numbers and other symbols), checks if it is a palindrome, and pushes it to the stack only if its palindrome.
void push(String str) {
if (isPalindrom(str)) {
words[++size] = str;
}
}
boolean isPalindrom(String str) {
// filters it from any non-alphabetic characters (i.e. remove numbers and other symbols)
str = str.replaceAll("[^a-zA-Z]", "");
// checks if it is a palindrom
return new StringBuilder(str).reverse().toString().equals(str);
}
// A method named pop() that returns the word on top of the stack and removes it from the stack.
String pop() {
String str = words[size--];
return str;
}
}
That's stackOfPalindromes class