Ignore a letter in isPalindrome() method - Java - java

I am wondering how the following method could be modified to ignore a certain letter and have it as a wildcard when checking if a string is a palindrome...
example: "wows", in this case the method should return false but
"pat" , the 't' can be a wildcard (considered as a p) and therefore it returns true
"job" , again the b can be a wildcard and considered as a j, therefore method returns true.
this is what i have so far, i have a seperate method ignoring special characters and spaces so that does not need to be considered in this post.
private static boolean checkPalindrome2(String word) {
if(word.length() < 2) {
return true;
}
char first = word.charAt(0);
char last = word.charAt(word.length()-1);
if(first != last) {
return false;
}
else {
return checkPalindrome2(word.substring(1,word.length()-1));
}
}
this is my test class,
public class testPalindromes {
public static void main(String[] args) {
//if (Palindromes.isPalindrome("a") == true) {
// System.out.println("true");
//} else {
// System.out.println("false");
//}
// block above is the same as this
// isPalindrome already returns true or false,
// and true and false can be printed as strings
System.out.println(isPalindrome("a"));
if (Palindromes.isPalindrome("cat") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Palindromes.isPalindrome("w o w") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Palindromes.isPalindrome(" a ") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Palindromes.isPalindrome("mom!") == true) {
System.out.println("true");
if (Palindromes.isPalindrome2("cat")==true){
System.out.print("true");
} else {
System.out.println("false");
}
}
}
}
isPalindromes2 is a method calling the checkPalindrome2 method above, the last case in my test class (word cat) should return true because the t will be the wildcard letter (wildcard again as stated above, replaced with c making cat, cac which is a palindrome)
thanks in advance for all help / input!!!!
ps, i purposely implemented a recursive method.

Just add extra conditions to your base case:
// both first and last have to NOT be the special character
// and first has to not equal last for this to return false
if(first != special && last != special && first != last)
return false;
else
return checkPalindrome(word.substring(1,word.length()-1));

Related

How do I check if a method returns a true or false?

So I have this code
public static boolean isVowel (char c) {
if (c=='a'||c=='e'||c=='i'||c=='o'||c=='u')
{
return true;
}
else
{
return false;
}
}
and this code in two seperate methods
if (isVowel == true()) //I know this is wrong but how could I make it work?
{
//run command
}
else
{
//run command
}
how could I make if (isVowel()) test if if isVowel true?
public static boolean isVowel (char c) {
// concise code here
return (c=='a'|| c=='e'|| c=='i'|| c=='o'|| c=='u');
}
// your fix here
if (isVowel(aCharVariable)) {
// your code here
} else {
// your code here
}
Concise and simple.
I don't know if I got the question right but here is what I think meets your requirements:
if (isVowel(/* put a char here */) == true) {
// Do stuff
} else {
// Do other stuff
}
In this case (because isVowel() is of type boolean you can also do this which is more elegant:
if (isVowel(/* put a char here */)) {
// Do stuff...
This is possible because the if statement checks for conditions which is nothing else than a boolean state (true or false).
In Java, an if statement checks whether its operand is true or false. Operands can only be of type boolean (and to a certain extent the boxed Boolean variant).
boolean b = true;
if (b) {
System.out.println("b was true");
}
Instead of assigning the static value/the literal true to the variable, you can also assign the result of a method call:
boolean b = isVowel('a');
if (b) {
System.out.println("a is a vowel");
}
Now, you do not necessarily need the variable, you can inline it and use the result of the method call directly:
if (isVowel('e')) {
System.out.println("e is a vowel too");
}
Note that some operators, such as ==, !=, <, return boolean values as well:
boolean greater = 5 > 3;
boolean equal = null == null;
boolean different = new Object() == new Object();
if (greater) {
System.out.println("5 is greater than 3");
}
if (equal) {
System.out.println("null equals null");
}
if (different) {
System.out.println("Two object instances have different idententity");
}
Of course, you do not need variables here and can put the comparison expression directly into the if:
if (5 > 3) {
System.out.println("5 is greater than 3");
}
if (null == null) {
System.out.println("null equals null");
}
if (new Object() == new Object()) {
System.out.println("Two object instances have different idententity");
}
or even:
if ((5 < 3) == false) {
System.out.println("The (logical) statement '5 is less than 3' is false. Therefore, the result of the boolean comparison is true and this code is executed");
}
Another way to write it that gets rid of all the ors.
private static final Set<Character> VOWELS = ImmutableSet.of('a','e','i','o','u');
public boolean isVowel(char c) {
return VOWELS.contains(c);
}
if(isVowel('a')) {
//do stuff
}

Java Stacks/Cannot Find Logic Error

For my CS class, I had to create a boolean function isBalanced(String x) that takes a string and evaluates the amount of brackets/parentheses and returns true if the brackets match up to its pair (e.g; { is a pair of }, ( is a pair of ), [ is a pair of ], etc.). The function would return true if the brackets correctly matched up, false if otherwise. For clarification, MyStack() is my own implementation of the Java stack interface if you are wondering what that Object was.
Examples of how the code would work and return:
{A(B[C])D} would return true.
{A(B[C)]D} would return false.
The problem in my code is a logic error. For some reason, my function is returning true if there is a missing bracket, which should return false.
{A(B)C would return false, but my code reads it as true. Do you have any solutions that would help my code work properly? Thanks!
Balancer.java
public static boolean isBalanced(String x) {
MyStack<String> stack = new MyStack();
if (x.substring(0,1).equals("}") || x.substring(0,1).equals(")") || x.substring(0,1).equals("]")) {
return false;
}
for (int i=0; i<x.length(); i++) {
if (x.substring(i,i+1).equals("{") || x.substring(i,i+1).equals("(") || x.substring(i,i+1).equals("[")) {
stack.add(x.substring(i,i+1));
}
if (x.substring(i,i+1).equals("}") || x.substring(i,i+1).equals(")") || x.substring(i,i+1).equals("]")) {
if (x.substring(i,i+1).equals("}") && stack.peek().equals("{")) {
stack.pop();
} else if (x.substring(i,i+1).equals(")") && stack.peek().equals("(")) {
stack.pop();
} else if (x.substring(i,i+1).equals("]") && stack.peek().equals("[")) {
stack.pop();
} else {
return false;
}
}
}
return true;
}
This file, labeled Main.java, is just a tester. I have omitted the other cases where the code works. The reason why the function should return false is that there is a missing } which should be at the end, but there is none, yet my function returns true for some reason.
Main.java
public static void main(String[] args) {
...
String test4 = "{AA[B(CDE{FG()T})V]";
System.out.println("Missing final close (empty stack case)");
System.out.println("Should be false, is: " + Balancer.isBalanced(test4)); // does not work
}
You have a series of conditions that only pop the stack if a matching pair of brackets are found. I think you're overcomplicating things - if an opening bracket is found, push it to the stack. If a closing parenthesis is found, pop the stack and make sure that they match. E.g.:
private static final Map<Character, Character> CLODSE_TO_OPEN = new HashMap<>();
static {
CLODSE_TO_OPEN.put(')', '(');
CLODSE_TO_OPEN.put(']', '[');
CLODSE_TO_OPEN.put('}', '{');
}
public static boolean isBalanced(String x) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < x.length(); ++i) {
char c = x.charAt(i);
if (CLODSE_TO_OPEN.containsValue(c)) {
stack.push(c);
} else if (CLODSE_TO_OPEN.containsKey(c)) {
try {
if (!CLODSE_TO_OPEN.get(c).equals(stack.pop())) {
return false;
}
} catch (EmptyStackException e) {
return false;
}
}
}
return stack.isEmpty();
}

What is wrong with my method isReverse

Write a recursive method called isReverse("word1", "word2") that accepts two Strings as parameters and returns true if the two Strings contain
the same sequence of characters as each other but in opposite order, ignoring case, and returning false otherwise.
For example, the call of:
isReverse("Desserts", "Stressed")
would return true. [So eat desserts when you are stressed?]
Null, empty and one letter strings are also to return true (if both parameters are the same value).
This is homework and I am having trouble making this code work appropriately. It returns true no matter what I do.
public static boolean isReverse(String word1, String word2)
{
if(word1 == null || word2 == null)
{
if(word1!= null && word2 != null)
{
return false;
}
return false;
}
else if(word1.length() == word2.length())
{
String firstWord = word1.substring(0, word1.length());
String secondWord = word2.substring(word2.length()-1);
if (firstWord.equalsIgnoreCase(secondWord))
{
return isReverse(word1.substring(0, word1.length()), word2.substring(word2.length() - 1));
}
}
return true;
}
First, you have this set so that it will only return false if both words are null; If they are not null you're re-calling the method(in the event that the length is equal), which will return true.
private static boolean isReverse(String a, String b) {
// make sure the strings are not null
if(a == null || b == null) return false;
// If the lengths are not equal, the strings cannot be reversed.
if(a.length() != b.length()) {
return false;
}
// Convert string b to an array;
char[] bArray = b.toCharArray();
// Create an array to write bArray into in reverse.
char[] copy = new char[bArray.length];
// Iterate through bArray in reverse and write to copy[]
for(int i = bArray.length; i < 0; i--) {
copy[bArray.length - i] = bArray[i];
}
// Convert copy[] back into a string.
String check = String.valueOf(copy);
// See if they reversed string is equal to the original string.
if(check.equalsIgnoreCase(a)) {
return true;
} else {
return false;
}
}
You are saying
if (firstWord.equalsIgnoreCase(secondWord))
{
return isReverse(word1.substring(0, word1.length()), word2.substring(word2.length() - 1));
}
which is OK. But what if firstWord does not equal second word
It falls through and returns true.
You need to add an
else
return false;
I will also add that your null checking will not work.
if(word1!= null && word2 != null)
{
return false;
}
Is not useful because you are already in an if that only happens when word1 or word2 is null. So they can't be null and null here.
It would work if you made it
if(word1 == null && word2 == null)
{
return true;
}
Is this an exercise? Recursion doesn't seems to be the best option here. Anyway, you're just trimming one word, why? You must trim both words if you expect to compare each char in each recursive call. And you're not even passing the trimmed words as parameter to the recursive function!
The basic thing you're missing is a base case. When the recursion must return? In your case, you're reducing each string size at each step of recursion, so you must have a base case to check if the size is one.
Hope that this code clear your mind:
public static boolean isReverse(String word1, String word2) {
if (word1 == null || word2 == null) {
return false;
}
if (word1.length() == 1 && word2.length() == 1) {
//Used equals just for fast compare
return word1.equals(word2);
} else if (word1.length() == word2.length()) {
if (word1.charAt(0) == word2.charAt(word2.length() - 1)) {
String firstWord = word1.substring(1, word1.length());
String secondWord = word2.substring(0, word2.length() - 1);
System.out.printf("Trimmed %s, %s to %s, %s\n", word1, word2, firstWord, secondWord);
return isReverse(firstWord, secondWord);
} else {
//Characters didn't matched
return false;
}
} else {
//Lenght doesn't match
return false;
}
}
First I have reversed one of the string(i took word1) using recursion.then compared to second string if both strings are equal result set to true.
public static boolean isReverse(String word1, String word2)
{
boolean result = false;
//check null to avoid null pointer exception
if(word1 == null | word2 == null){
result = false;
}else if(word1.length() == word2.length()){
word1 = reverseString(word1);
if(word1.equalsIgnoreCase(word2)){
result = true;
}
}
return result;
}
static String reverse = "";
public static String reverseString(String str){
if(str.length() == 1){
reverse+=str;
} else {
reverse += str.charAt(str.length()-1)
+reverseString(str.substring(0,str.length()-1));
}
return reverse;
}

How to compare three boolean values

Compare three boolean values and display the first one that is true.
Hey guys, I am trying to write a program that compares three boolean values and displays the first true one. I am comparing three words for their length, and it will display the longest. The error that I am getting is that my else tags aren't working. Take a look at the code.
//Check which word is bigger
if (len1 > len2)
word1bt2 = true;
if (len2 > len3)
word2bt3 = true;
if (len1 > len3)
word1bt3 = true;
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true);
System.out.println(wor1);
else if (word2bt3 == true);
System.out.println(wor2);
else System.out.println(wor3);
I have set boolean values for word1bt2, word2bt3 and word1bt3. In eclipse, I am getting a syntax error under the elses in my code above. Any help would be great!
if (word1bt2 == true && word1bt3 == true);
Is wrong, you need to remove the semicolon:
if (word1bt2 == true && word1bt3 == true)
Same for the elses
else (word2bt3 == true);
Is wrong too, it should be
else if (word2bt3 == true)
Side note: boolean values can be used as condition, so your if statements should be
if (word1bt2 && word1bt3) // The same as if (word1bt2 == true && word1bt3 == true)
How to compare three boolean values?
Dont!
If you find yourself needing to compare three variable you may as well cater for any number of variables immediately - there's no point hanging around - do it properly straight away.
public String longest(Iterator<String> i) {
// Walk the iterator.
String longest = i.hasNext() ? i.next() : null;
while (i.hasNext()) {
String next = i.next();
if (next.length() > longest.length()) {
longest = next;
}
}
return longest;
}
public String longest(Iterable<String> i) {
// Walk the iterator.
return longest(i.iterator());
}
public String longest(String... ss) {
// An array is iterable.
return longest(ss);
}
Remove the ; and change it with brackets {}.
if (word1bt2 && word1bt3) {
System.out.println(wor1);
} else if (word2bt3) {
System.out.println(wor2);
} else {
System.out.println(wor3);
}
Issue with the else blocks: use {} insteaad of () to enclose instructions...
Remove the ; at the first if!!!!! - Quite common mistake, with very puzzling results!
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true) { //leave ; and always add bracket!
System.out.println(wor1);
}
else if(word2bt3 == true)
{
System.out.println(wor2);
}
else {
System.out.println(wor3);
}
if you need a condition in an else branch, you have to use if again - plain else won't have such a feature...
ALWAYS use brackets for bodies of if statements, loops, etc!!!
Be extremely careful NOT to use ; in the lines that don't behave well with it:
if statements
for loops
while() {...} loops' while statement
try this, if lenght are equal then s1 is considered as Bigger. Also i have not added null check
public class Test {
public static void main(String[] args) {
String word1 = "hi";
String word2 = "Hello";
String word3 = "Hell";
String Bigger = null;
if(word1.length() >= word2.length() && word1.length() >= word3.length() ){
Bigger = word1;
}else if(word2.length() >= word1.length() && word2.length() >= word3.length()){
Bigger = word2;
}else if(word3.length() >= word2.length() && word3.length() >= word1.length()){
Bigger = word3;
}
System.out.println(Bigger);
}
}

Recursive Function : Check for palindrome in Java

I have a class that checks whether a string is a palindrome or not. I have two questions.
1) Is this the most efficient way to check for palindrome?
2) Can this be implemented recursively?
public class Words {
public static boolean isPalindrome(String word) {
String pal = null;
word = word.replace(" ", "");
pal = new StringBuffer(word).reverse().toString();
if (word.compareTo(pal) == 0) {
return true;
} else {
return false;
}
}
}
Have a test class to test this... Doubt its needed but here it is anyways if anyone cares to try it out to be able to help me with any of the two questions above...
public class testWords {
public static void main(String[] args) {
if (Words.isPalindrome("a") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome("cat") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome("w o w") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome(" a ") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
if (Words.isPalindrome("mom!") == true) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
thanks in advance for any help and or input :)
To implement a 'palindrome check' recursively, you must compare if the first and last characters are the same. If they are not the same the string is most certainly not a palindrome. If they are the same the string might be a palindrome, you need to compare the 2nd character with the 2nd to last character, and so on until you have strictly less then 2 characters remaining to be checked in your string.
A recursive algorithm would look like this:
public static boolean isPalindrome(String word) {
//Strip out non-alphanumeric characters from string
String cleanWord = word.replaceAll("[^a-zA-Z0-9]","");
//Check for palindrome quality recursively
return checkPalindrome(cleanWord);
}
private static boolean checkPalindrome(String word) {
if(word.length() < 2) { return true; }
char first = word.charAt(0);
char last = word.charAt(word.length()-1);
if( first != last ) { return false; }
else { return checkPalindrome(word.substring(1,word.length()-1)); }
}
Note, that my recursion method is not most efficient approach, but
simple to understand
Marimuthu Madasamy has a more efficient recursive method, but is harder to understand
Joe F has listed an equivalently efficient iterative method
which is the best approach for implementation because it cannot cause a stack overflow error
Here is another recursive solution but using array which could give you some performance advantage over string in recursive calls (avoiding substring or charAt).
private static boolean isPalindrome(final char[] chars, final int from,
final int to) {
if (from > to) return true;
return chars[from] != chars[to] ? false
: isPalindrome(chars, from + 1, to - 1);
}
public static boolean isPalindrome(final String s) {
return isPalindrome(s.toCharArray(), 0, s.length() - 1);
}
The idea is that we keep track of two positions in the array, one at the beginning and another at the end and we keep moving the positions towards the center.
When the positions overlap and pass, we are done comparing all the characters and all the characters so far have matched; the string is palindrome.
At each pass, we compare the characters and if they don't match then the string is not palindrome otherwise move the positions closer.
It's actually sufficient to only check up to the middle character to confirm that it is a palindrome, which means you can simplify it down to something like this:
// Length of my string.
int length = myString.length();
// Loop over first half of string and match with opposite character.
for (int i = 0; i <= length / 2; i++) {
// If we find one that doesn't match then return false.
if (myString.charAt(i) != myString.charAt(length - 1 - i)) return false;
}
// They all match, so we have found a palindrome!
return true;
A recursive solution is very possible but it is not going to give you any performance benefit (and probably isn't as readable).
Can this be implemented Recursively?
YES
Here is example:
public static boolean palindrome(String str)
{
if (str.length()==1 || str.length == 0)
return true;
char c1 = str.charAt(0);
char c2 = str.charAt(str.length() - 1);
if (str.length() == 2)
{
if (c1 == c2)
return true;
else
return false;
}
if (c1 == c2)
return palindrome(str.substring(1,str.length() - 1));
else
return false;
}
My two cents. It's always nice to see the different ways people solve a problem. Of course this is not the most efficient algorithm memory or speed wise.
public static boolean isPalindrome(String s) {
if (s.length() <= 1) { // got to the middle, no need for more checks
return true;
}
char l = s.charAt(0); // first char
char r = s.charAt(s.length() - 1); // last char
if (l == r) { // same char? keep checking
String sub = s.substring(1, s.length() - 1);
return isPalindrome(sub);
}
return false;
}
The simplest way to check palindrome.
private static String palindromic(String word) {
if (word.length() <= 1) {
return "Polidramic";
}else if (word.charAt(0) != word.charAt(word.length() - 1)) {
return "Not Polidramic";
}
return palindromic(word.substring(1, word.length() - 1));
}

Categories