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 <stdio.h>
2#include <string.h>
3
4int isPalindrome(char *s) {
5 int i = 0, j = strlen(s) - 1;
6 while (i < j) {
7 if (s[i] != s[j]) return 0;
8 i++;
9 j--;
10 }
11 return 1;
12}
13
14char* firstPalindrome(char** words, int wordsSize) {
15 for (int i = 0; i < wordsSize; i++) {
16 if (isPalindrome(words[i])) {
17 return words[i];
18 }
19 }
20 return "";
21}
The function isPalindrome
uses two pointers to check each character from both ends of a string. If they match all through, the string is a palindrome. The firstPalindrome
function iterates through the list of words and returns the first palindromic string it finds.
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 JavaScript code reverses each word using the split
, reverse
, and join
methods and checks equality with the original to determine palindromes.