Skip to content

Commit f37e145

Browse files
#703 solved
1 parent 100d6aa commit f37e145

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Arrays/add_valid_palindrome.java

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
Write a function that takes a string as input and checks whether it can be a valid palindrome by removing at most one character from it.
3+
Example 1:
4+
5+
Input: s = "aba"
6+
Output: true
7+
*/
8+
9+
class Solution {
10+
public boolean validPalindrome(String s) {
11+
int i=0,j=s.length()-1; // initialize two pointers, i and j to the start and end of the string respectively
12+
while(i<j){ // loop until i is less than j
13+
if(s.charAt(i)!=s.charAt(j)) // if the characters at i and j are not equal
14+
return isPalindrome(s,i+1,j) || isPalindrome(s,i,j-1); // check if the string is a palindrome by removing either the character at i or j and return true if it is a palindrome
15+
j--;i++; // update the pointers
16+
}
17+
return true; // if the loop completes without returning false, the string is a palindrome
18+
}
19+
public static boolean isPalindrome(String ss,int i, int j){ // a helper function to check if a given substring is a palindrome
20+
while(i<j){
21+
if(ss.charAt(i)!= ss.charAt(j)) return false; // if the characters at i and j are not equal, the substring is not a palindrome
22+
i++;j--; // update the pointers
23+
}
24+
return true; // if the loop completes without returning false, the substring is a palindrome
25+
}
26+
}
27+

0 commit comments

Comments
 (0)