Input: words =["abc","car","ada","racecar","cool"]Output: "ada"Explanation: The first string that is palindromic is"ada".Note that "racecar"is also palindromic, but it is not the first.
Example 2:
1
2
3
4
Input:
words =["notapalindrome","racecar"]Output: "racecar"Explanation: The first and only string that is palindromic is"racecar".
Example 3:
1
2
3
Input: words =["def","ghi"]Output: ""Explanation: There are no palindromic strings, so the empty string is returned.
publicclassSolution {
public String firstPalindrome(String[] words) {
for (String word : words) {
if (isPalindrome(word)) {
return word;
}
}
return"";
}
privatebooleanisPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) {
returnfalse;
}
left++;
right--;
}
returntrue;
}
}
1
2
3
4
5
6
7
8
9
classSolution:
deffirstPalindrome(self, words: List[str]) -> str:
for word in words:
if self.is_palindrome(word):
return word
return""defis_palindrome(self, s: str) -> bool:
return s == s[::-1]
⏰ Time complexity: O(n * m), where n is the number of strings and m is the average length of the strings. This accounts for the iteration over each string and checking if it is a palindrome.
🧺 Space complexity: O(1), since we are only using a constant amount of extra space for variables, excluding the space required for input storage.