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
This Java solution utilizes StringBuilder
to reverse the string and checks if it matches the original word. The first matching palindrome word is returned.