Sponsored
Sponsored
This approach involves checking each string using a two-pointer technique. You set one pointer at the start and one at the end of the string and compare characters. If all characters match until the pointers cross, the string is a palindrome.
Time Complexity: O(n * m), where n is the number of words and m is the average length of the words.
Space Complexity: O(1) because it uses constant space.
1#include <iostream>
2#include <vector>
3#include <string>
4
5using namespace std;
6
7bool isPalindrome(const string &s) {
8 int i = 0, j = s.size() - 1;
9 while (i < j) {
10 if (s[i++] != s[j--]) {
11 return false;
12 }
13 }
14 return true;
15}
16
17string firstPalindrome(vector<string>& words) {
18 for (const auto &word : words) {
19 if (isPalindrome(word)) {
20 return word;
21 }
22 }
23 return "";
24}
The isPalindrome
function uses two index pointers to compare characters from both ends of a string. If matched till the pointers met or cross, the function returns true, indicating a palindrome. The function firstPalindrome
finds the first such word in the array and returns it.
This method leverages string reversal to check if a word is a palindrome. You can reverse the string and compare it with the original; if they are the same, it's a palindrome.
Time Complexity: O(n * m), where n is the number of words and m is the length of words.
Space Complexity: O(m) due to the additional string for reversal.
1
This Python solution reverses each word and compares it to itself. If they're equal, it is palindromic, and the word is returned.