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.
1public class Solution {
2 public String firstPalindrome(String[] words) {
3 for (String word : words) {
4 if (isPalindrome(word)) {
5 return word;
6 }
7 }
8 return "";
9 }
10
11 private boolean isPalindrome(String s) {
12 int i = 0, j = s.length() - 1;
13 while (i < j) {
14 if (s.charAt(i++) != s.charAt(j--)) {
15 return false;
16 }
17 }
18 return true;
19 }
20}
This Java solution employs a helper method isPalindrome
, which uses a two-pointer technique to validate if a string is a palindrome. The firstPalindrome
method iterates over the array to find and return the first palindrome 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.