Advertisement
LikeRampage

Python3 Leetcode 336. Palindrome Pairs Chatgpt

May 2nd, 2024
537
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. class Solution:
  2.     def palindromePairs(self, words: List[str]) -> List[List[int]]:
  3.         def is_palindrome(word):
  4.             return word == word[::-1]
  5.  
  6.         word_dict = {word: i for i, word in enumerate(words)}
  7.         result = []
  8.  
  9.         for i, word in enumerate(words):
  10.             for j in range(len(word) + 1):
  11.                 prefix = word[:j]
  12.                 suffix = word[j:]
  13.                 if is_palindrome(prefix):
  14.                     reversed_suffix = suffix[::-1]
  15.                     if reversed_suffix != word and reversed_suffix in word_dict:
  16.                         result.append([word_dict[reversed_suffix], i])
  17.                 if j != len(word) and is_palindrome(suffix):
  18.                     reversed_prefix = prefix[::-1]
  19.                     if reversed_prefix != word and reversed_prefix in word_dict:
  20.                         result.append([i, word_dict[reversed_prefix]])
  21.  
  22.         return result
Tags: python3
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement