I want to find if a string contains a palindrome word. An example would be hellosannasmith
contains a palindrome word and should return sannas
, however givemefood
should return none
. I first tried it through 2 for loops then I started to think why not a while loop but before I begin going the while loop route I want to see if it can be done in 2 for loops first.
I managed to get san
into the new palindrome string variable but I’m not sure what else I am missing or overlooking here. Any help would be greatly appreciated.
function SearchingChallenge(str) {
var palindromeStr = "";
for (var i = 0; i < str.length / 2; i++) {
for (var j = str.length - 1; str.length / 2 < j; j--) {
if (str[i + 1] == str[j - 1] && str[i] == str[j]) {
palindromeStr += str[i];
}
}
}
if (palindromeStr == "") {
return "none";
}
return palindromeStr;
}
console.log(SearchingChallenge('hellosannasmith'));
console.log(SearchingChallenge('givemefood'));
3
Answers
You can define a
Set()
including all the words and then use dynamic programming to find the longest palindrome.You can also add some conditions to return a palindrome, once found in the set. (It’s unclear from the question).
Note:
Something to consider is that your outer loop is only looking at the first half of the string and the inner loop is only looking at the second half of the string, meaning you are not checking for all possible substrings. Your approach is only considering whether one exists at the center of the string.
Another note is that your condition
if(str[i + 1] == str[j - 1] && str[i] == str[j])
is only checking pairs of characters at a specified position. So you are doing a partial character check, not an entire substring. So you end up building your string when two pairs match, which does not guarantee it’s a palindrome.Try making it more readable and robust by adjusting your loops:
Then you can build your substring using those indices
First, by comparing str[i] = str[j] you can come to "polindrom" without having a polindrom. imaging "abcdefcba": for i=1,2,3, j=n-1,n-2,n-3 str[i] === str[j]. however they not connected, because in between you have other stuff.
Secondly, in the same check you checking both
str[i]===str[j]
andstr[i+1]===str[j-1]
means the last char answering the criteria will not be entering the result (apart when they meet at the center, like your first example)So what you have to do is to check for every given interval if a substring in the given interval is a polindrom.
Check the below example:
Lastly, remeber two things:
givemefood
,eme
is a polyndrom then. in above example min polyndrom length set ton three. but it need to be defined