Skip to content

Commit ece153f

Browse files
#647 solved
1 parent cab11cb commit ece153f

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Arrays/valid_palindrome.java

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Two Pointers: Check whether a given string is a Valid Palindrome in Java
3+
*/
4+
5+
6+
7+
8+
public static boolean isPalindrome(String str)
9+
{
10+
// initialize startIdx to 0 and endIdx to the last index in the string
11+
int startIdx = 0;
12+
int endIdx = str.length() - 1;
13+
14+
// loop through the string while the start index is less than the end index
15+
while(startIdx < endIdx)
16+
{
17+
// get the characters at the start and end indices
18+
char start = str.charAt(startIdx);
19+
char end = str.charAt(endIdx);
20+
21+
// if the lowercase versions of the characters do not match, return false
22+
if(Character.toLowerCase(start) != Character.toLowerCase(end))
23+
return false;
24+
25+
// increment the start index and decrement the end index
26+
startIdx += 1;
27+
endIdx -= 1;
28+
}
29+
30+
// if the loop completes without returning false, the string is a palindrome so return true
31+
return true;
32+
}
33+
34+
35+
/* EXPLAINATION:
36+
The function isPalindrome takes a String input and returns a boolean indicating whether the input string is a palindrome or not.
37+
38+
The function initializes two integer variables, startIdx and endIdx, to the first and last indices in the string, respectively. It then enters a loop that continues while startIdx is less than endIdx.
39+
40+
Inside the loop, the function gets the characters at the start and end indices using the charAt method. It then checks if the lowercase versions of these characters match using the toLowerCase method. If they do not match, the function immediately returns false, indicating that the string is not a palindrome.
41+
42+
If the loop completes without returning false, the function returns true, indicating that the input string is a palindrome.
43+
44+
The time complexity of the function is O(n), where n is the length of the input string. This is because the function loops through half the length of the string in the worst case.
45+
46+
The space complexity of the function is O(1), as it uses a constant amount of additional memory to keep track of the start and end indices.
47+
*/

0 commit comments

Comments
 (0)