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 foreach (var word in words) {
4 if (IsPalindrome(word)) {
5 return word;
6 }
7 }
8 return "";
9 }
10
11 private bool IsPalindrome(string s) {
12 int i = 0, j = s.Length - 1;
13 while (i < j) {
14 if (s[i++] != s[j--]) {
15 return false;
16 }
17 }
18 return true;
19 }
20}
This C# solution uses the helper method IsPalindrome
with a two-pointer approach for palindrome validation. The main method, FirstPalindrome
, finds the first such palindrome if it exists.
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.