Search code examples
javascriptalgorithmpalindrome

Checking if a word in string contains a palindrome


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'));


Solution

  • First, by comparing str[i] = str[j] you can come to "palindrome" without having a palindrome. 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] and str[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 palindrome.

    Check the below example:

    function isPalindrome(str) {
      return str === str.split('').reverse().join('');
    }
    
    function SearchingChallenge(str) {
    
      if(str.length <= 1) return 'none';
      
      for(let i=0;i<str.length-3;i++) {
        for(let j=str.length-1; j>i+2; j--) {
            
            const substr = str.substring(i, j);
            if(isPalindrome(substr)) return substr;
        }
      }
    
      return 'none';
    }
    
    console.log(SearchingChallenge('hellosannasmith'));
    console.log(SearchingChallenge('givemefood'));
    console.log(SearchingChallenge('abcdef'));
    console.log(SearchingChallenge('someawesomeemosik'));

    Lastly, remember two things:

    1. There can be more then one palindrome in the string. so you have to decide weather you return the first instance, or you return array of all found palindromes. (in the example above i returning first found)
    2. You should define minimum chars of the accepted palindrome. Probably 1char you dont wanna consider palindrome. how about 2? "aa" is a palindrome? and 3? in your second example, givemefood, eme is a palindrome then. in above example min palindrome length set ton three. but it need to be defined