First Palindromic String in the Array

easy string two pointers

Problem

Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string "".

A string is a palindrome if it reads the same forwards and backwards. Check each word with two pointers that close in from both ends; return the first word that survives the check.

Input["abc", "car", "ada", "racecar", "cool"]
Output"ada"
"abc" and "car" are not palindromes; "ada" is the first one that is.

def first_palindrome(words):
    for w in words:
        i, j = 0, len(w) - 1
        while i < j and w[i] == w[j]:
            i += 1
            j -= 1
        if i >= j:
            return w
    return ""
function firstPalindrome(words) {
  for (const w of words) {
    let i = 0, j = w.length - 1;
    while (i < j && w[i] === w[j]) { i++; j--; }
    if (i >= j) return w;
  }
  return "";
}
class Solution {
    public String firstPalindrome(String[] words) {
        for (String w : words) {
            int i = 0, j = w.length() - 1;
            while (i < j && w.charAt(i) == w.charAt(j)) { i++; j--; }
            if (i >= j) return w;
        }
        return "";
    }
}
string firstPalindrome(vector<string>& words) {
    for (string& w : words) {
        int i = 0, j = (int)w.size() - 1;
        while (i < j && w[i] == w[j]) { i++; j--; }
        if (i >= j) return w;
    }
    return "";
}
Time: O(total characters) Space: O(1)