Skip to content

Commit 96c0cd4

Browse files
committed
Palindrome checker - alternative
1 parent cfc601c commit 96c0cd4

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

src/easy/Palindrome.java

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,25 @@ private static String palindrome(String str) {
2424
return cleaned.equals(reversed.toString()) && str.length() > 0 ? "true" : "false";
2525
}
2626

27+
/**
28+
* An improved function checking if a given string is a palindrome.
29+
* It compares two halves of a string, checking if a letter
30+
* from the first half matches the other half in the reverse order.
31+
*
32+
* @param str input string
33+
* @return true if the string is a palindrome
34+
*/
35+
private static boolean isPalindrome(String str) {
36+
char[] strArr = str.toCharArray();
37+
int len = strArr.length;
38+
for (int i = 0; i < len / 2; i++) {
39+
if (strArr[i] != strArr[len - i - 1]) {
40+
return false;
41+
}
42+
}
43+
return true;
44+
}
45+
2746
/**
2847
* Entry point.
2948
*
@@ -32,8 +51,12 @@ private static String palindrome(String str) {
3251
public static void main(String[] args) {
3352
var result1 = palindrome("dont nod");
3453
System.out.println(result1);
35-
var result2 = palindrome("rats live on no evil star");
54+
var result2 = isPalindrome("dont nod");
3655
System.out.println(result2);
56+
var result3 = palindrome("rats live on no evil star");
57+
System.out.println(result3);
58+
var result4 = isPalindrome("rats live on no evil star");
59+
System.out.println(result4);
3760
}
3861

3962
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy