'Is this a valid solution to the palindrome problem?
Is my solution down below valid or am I relying too much on built in functions? Just to give some context, suppose this was an interview question or something of similar magnitude.
public static boolean palindrome(String s){
char[] arr = new char[s.length()];
for (int i = 0; i < s.length(); i++) {
arr[i] = s.charAt(s.length() - 1 - i);
}
return s.compareTo(String.valueOf(arr)) == 0;
}
Solution 1:[1]
I don't claim this to be most optimal, but I will share it with you as I think it might be better than your answer.
If you think of a String as an array of characters, what if you create two pointers, one that points to the head and one that points to the tail and do a character-by-character comparison until the pointer indexes are the same or the tail pointer is lower than the head? This is how that looks in code:
import java.util.List;
public class PalindromeDemo {
public static void main(String[] args) {
List<String> inputs = List.of("Otto", "Hello", "Delia saw I was ailed");
for (String s : inputs) {
System.out.println(s + " is palindrome? " + isPalindrome(s));
}
}
public static boolean isPalindrome(String s) {
int headPtr = 0;
int tailPtr = s.length() - 1;
char[] chars = s.toLowerCase().toCharArray();
while (headPtr < tailPtr) {
if (chars[headPtr] != chars[tailPtr]) {
return false;
}
headPtr++;
tailPtr--;
}
return true;
}
}
You may have to ask if the solution need to be case-sensitive. My solution is not. Most times when I have seen this question, the person asking is interested in a case-insensitive solution. That's why I called toLowerCase(). Also (not that it matters that much), this solution doesn't reverse the string. It simply walks two pointers and compare the characters each one is pointing to. If a mismatch is encounter, I break immediately. That's why I think this solution is a bit more effective. I also don't need to use a comparator class.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
