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.
1function isPalindrome(s) {
2 let left = 0, right = s.length - 1;
3 while (left < right) {
4 if (s[left++] !== s[right--]) {
5 return false;
6 }
7 }
8 return true;
9}
10
11function firstPalindrome(words) {
12 for (const word of words) {
13 if (isPalindrome(word)) {
14 return word;
15 }
16 }
17 return "";
18}
This JavaScript solution uses an isPalindrome
function to verify if a word is a palindrome using a two-pointer method. firstPalindrome
iterates over the input array to return the first palindromic word.
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#include <vector>
#include <string>
using namespace std;
string reverse(const string &s) {
string rev = s;
reverse(rev.begin(), rev.end());
return rev;
}
string firstPalindrome(vector<string>& words) {
for (const auto &word : words) {
if (word == reverse(word)) {
return word;
}
}
return "";
}
This C++ solution reverses each word and compares it with the original. If they match, it returns the word as a palindrome.