Skip to content

Commit 5f03425

Browse files
committed
[Manan] ADD:Checking if the entered string is palindrome or not
1 parent dc23b75 commit 5f03425

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

PalindromeString.java

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import java.util.Scanner;
2+
3+
class PalindromeString {
4+
// Logic 1: using two-pointers approach
5+
public static boolean isPalindromeStringTwoPointer(String s) {
6+
int start = 0, end = s.length() - 1;
7+
while (start < end) {
8+
if (s.charAt(start) != s.charAt(end)) {
9+
return false;
10+
}
11+
start++;
12+
end--;
13+
}
14+
return true;
15+
}
16+
17+
// Logic 2: Using Recursion approach
18+
public static boolean isPalindromeStringRecursive(String s, int start, int end) {
19+
if (start >= end) {
20+
return true;
21+
}
22+
if (s.charAt(start) != s.charAt(end)) {
23+
return false;
24+
}
25+
return isPalindromeStringRecursive(s, start + 1, end - 1);
26+
}
27+
28+
// Logic 3: Using character array and reverse comparison approach
29+
public static boolean isPalindromeStringCharArray(String s) {
30+
char[] originalArray = s.toCharArray();
31+
char[] reversedArray = reverseString(s);
32+
33+
// Compare original and reversed arrays
34+
for (int i = 0; i < originalArray.length; i++) {
35+
if (originalArray[i] != reversedArray[i]) {
36+
return false;
37+
}
38+
}
39+
return true;
40+
}
41+
42+
// Method to reverse a string
43+
public static char[] reverseString(String s) {
44+
char[] reversed = new char[s.length()];
45+
for (int i = 0; i < s.length(); i++) {
46+
reversed[i] = s.charAt(s.length() - 1 - i);
47+
}
48+
return reversed;
49+
}
50+
51+
// Main method
52+
public static void main(String[] args) {
53+
Scanner input = new Scanner(System.in);
54+
55+
System.out.print("Enter a string: ");
56+
String userInput = input.nextLine();
57+
58+
// Checking using all three logic methods
59+
boolean result1 = isPalindromeStringTwoPointer(userInput);
60+
boolean result2 = isPalindromeStringRecursive(userInput, 0, userInput.length() - 1);
61+
boolean result3 = isPalindromeStringCharArray(userInput);
62+
63+
// Display results
64+
System.out.println("[Logic 1] Is the string a palindrome? " + result1);
65+
System.out.println("[Logic 2] Is the string a palindrome? " + result2);
66+
System.out.println("[Logic 3] Is the string a palindrome? " + result3);
67+
68+
// Compare the results
69+
if (result1 == result2 && result2 == result3) {
70+
System.out.println("All methods give the same result.");
71+
} else {
72+
System.out.println("Results are not the same.");
73+
}
74+
}
75+
}

0 commit comments

Comments
 (0)