How do you test if a given String is a palindrome in Java, without using any methods that do it all for me?
Asked
Active
Viewed 8,661 times
-6
-
7The community really isn't here to just give you complete code. Show us what you've tried and we will help you. Also this sounds like homework to me, but I'm not going to tag it yet. – Neil Aitken Aug 06 '10 at 06:38
-
What does it mean "without using APIs?" If it means what I think it means, then this problem is impossible. – emory Aug 06 '10 at 10:46
5 Answers
6
String palindrome = "..." // from elsewhere
boolean isPalindrome = palindrome.equals(new StringBuilder(palindrome).reverse().toString());

Noel M
- 15,812
- 8
- 39
- 47
-
2I guess that "without using API'S" means: without using for example `StringBuilder.reverse()`. – Jesper Aug 06 '10 at 13:07
5
public boolean checkPalindrome(string word){
for(int i=0 ; i < word.length()/2;i++)
{
if(word.charAt(i) ! = word.charAt(word.length()-1-i))
return false;
}
return true;
}

NullUserException
- 83,810
- 28
- 209
- 234

Egalitarian
- 2,168
- 7
- 24
- 33
0
Noel's solution is actually better. But if it's for homework, you might want to do this:
public static boolean isPalindrome(String word) {
int left = 0;
int right = word.length() -1;
while (left < right) {
if (word.charAt(left) != word.charAt(right))
return false;
left++;
right--;
}
return true;
}

Alon Gubkin
- 56,458
- 54
- 195
- 288
0
Java in-place palindrome check:
public static final boolean isPalindromeInPlace(String string) {
char[] array = string.toCharArray();
int length = array.length-1;
int half = Math.round(array.length/2);
char a,b;
for (int i=length; i>=half; i--) {
a = array[length-i];
b = array[i];
if (a != b) return false;
}
return true;
}

Justin
- 4,196
- 4
- 24
- 48
-2
String str="iai";
StringBuffer sb=new StringBuffer(str);
String str1=sb.reverse().toString();
if(str.equals(str1)){
System.out.println("polindrom");
} else {
System.out.println("not polidrom");
}

Jacob Schoen
- 14,034
- 15
- 82
- 102

Satish
- 1
- 2