-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindromeCheck.java
More file actions
44 lines (33 loc) · 1.34 KB
/
Copy pathPalindromeCheck.java
File metadata and controls
44 lines (33 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package javaStrings;
import java.util.stream.IntStream;
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String reverseStr = new StringBuilder(str).reverse().toString();
System.out.println("Is the string a palindrome? " + str.equalsIgnoreCase(reverseStr));
// Using simple loop
if(str.equalsIgnoreCase(reverseStr)) {
System.out.println("The string is a palindrome");
} else {
System.out.println("The string is not a palindrome");
}
boolean isPalindrome = true;
int length = str.length();
for (int i = 0; i < length / 2; i++) {
if (str.charAt(i) != str.charAt(length - i - 1)) {
isPalindrome = false;
break;
}
}
if(isPalindrome) {
System.out.println("The string is a palindrome");
} else {
System.out.println("The string is not a palindrome");
}
// Using Java 8
String cleanedStr = str.replaceAll("\\s+", "").toLowerCase(); // Normalize input
IntStream.range(0, cleanedStr.length() / 2)
.allMatch(i -> cleanedStr.charAt(i) == cleanedStr.charAt(cleanedStr.length() - 1 - i));
System.out.println(str + " is palindrome " );
}
}