When we hear the term "palindrome", it immediately brings to mind a string that reads the same forwards and backwards. To find the first palindromic string in an array, we can simply iterate through the array and check each string to see if it is a palindrome.
The approach used in the code is straightforward. We iterate over the array of words. For each word, we check if it is a palindrome by comparing each character from the start of the word with the corresponding character from the end of the word. If we find a pair of characters that do not match, we know the word is not a palindrome and we move on to the next word. If we reach the middle of the word without finding any mismatching characters, we know the word is a palindrome and we return it.
-
Time complexity: The time complexity is
$O(n*m)$ , where$n$ is the number of words in the array and$m$ is the average length of the words. -
Space complexity: The space complexity is
$O(1)$ , not considering the space required for the input and output.
class Solution {
public:
string firstPalindrome(vector<string>& words) {
for (int i = 0; i < words.size(); i++) {
bool check = true;
int n = words[i].size();
for (int j = 0; j <= (n / 2); j++) {
if (words[i][j] != words[i][n-j-1]) {
check = false;
break;
}
}
if (check) {
return words[i];
}
}
return "";
}
};