Simplest Solution EVER!!!


  • 0
    O

    All we need to do is to find the longest palindrome that starts from index 0 of string s. So how to do it?
    We just reverse string s and traverse through reversed string s(we will call it r). We simply compare sub-strings of r and s and if it is equal we finish while loop. The answer will be sub-string of r from 0 point to founded index added to string s.

    # @return {String}
    def shortest_palindrome(s)
      r = s.reverse
      i = 0
      len = s.size
      idx = 0
      while i < s.size
        if r[i, len] == s[0, len]
          idx = i
          break
        end
        i+=1
        len -= 1
      end
      return "#{r[0, idx]}#{s}"
    end```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.