Using the all characters of a given String how to specify either a palindrome or not.
Ex:-
1) String="teste"
After arrange all character we can made a palindrome String as "teset"
So output is TRUE.
2)String="hello"
we can not made a palindrome String
output is FALSE
Sort the given string and after call the below method
Ex:-
1) String="teste"
After arrange all character we can made a palindrome String as "teset"
So output is TRUE.
2)String="hello"
we can not made a palindrome String
output is FALSE
Sort the given string and after call the below method
boolean isFormingPalindrome(String s) {
//Assume we are taking sorted string as an argument
if (s == null || s.length() == 0 || s.length() == 1)
return true;
int length = s.length();
// if it has even number of characters,it should have zero non repeated
// characters. else it should have one non repeated character
boolean isFirstNonRepeated = false;
if (length % 2 == 0) {
// for even length,there will not be any
// non repeated characters
isFirstNonRepeated = true;
}
char[] characters = s.toCharArray();
for (int i = 1; i < length; i = i + 2) {
if (characters[i - 1] != characters[i]) {
if (isFirstNonRepeated) {
return false;
} else {
i = i - 1;
isFirstNonRepeated = true;
}
}
}
return true;
}
No comments:
Post a Comment