Skip to content

2108. Find First Palindromic String in the Array 👍

  • Time: $O(n)$
  • Space: $O(|\texttt{word}|)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  string firstPalindrome(vector<string>& words) {
    for (const string& word : words)
      if (isPalindrome(word))
        return word;
    return "";
  }

 private:
  bool isPalindrome(const string& s) {
    int i = 0;
    int j = s.length() - 1;
    while (i < j)
      if (s[i++] != s[j--])
        return false;
    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public String firstPalindrome(String[] words) {
    for (final String word : words)
      if (isPalindrome(word))
        return word;
    return "";
  }

  private boolean isPalindrome(final String s) {
    int i = 0;
    int j = 0;
    while (i < j)
      if (s.charAt(i++) != s.charAt(j--))
        return false;
    return true;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def firstPalindrome(self, words: List[str]) -> str:
    def isPalindrome(s: str) -> bool:
      i = 0
      j = len(s) - 1
      while i < j:
        if s[i] != s[j]:
          return False
        i += 1
        j -= 1
      return True
    return next((word for word in words if isPalindrome(word)), '')