Skip to content

Commit b393590

Browse files
Valid Palindrome II: Accepted
1 parent 9a13067 commit b393590

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ My accepted leetcode solutions to some of the common interview problems.
197197
- [Simplify Path](problems/src/string/SimplifyPath.java) (Medium)
198198
- [Permutation in String](problems/src/string/PermutationInString.java) (Medium)
199199
- [Add Binary](problems/src/string/AddBinary.java) (Easy)
200+
- [Valid Palindrome II](problems/src/string/ValidPalindromeII.java) (Easy)
200201

201202
#### [Tree](problems/src/tree)
202203

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package string;
2+
3+
/**
4+
* Created by gouthamvidyapradhan on 09/12/2017.
5+
* Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.
6+
7+
Example 1:
8+
Input: "aba"
9+
Output: True
10+
Example 2:
11+
Input: "abca"
12+
Output: True
13+
Explanation: You could delete the character 'c'.
14+
Note:
15+
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.
16+
*/
17+
public class ValidPalindromeII {
18+
19+
/**
20+
* Main method
21+
* @param args
22+
* @throws Exception
23+
*/
24+
public static void main(String[] args) throws Exception{
25+
System.out.println(new ValidPalindromeII().validPalindrome("aaaaaab"));
26+
}
27+
28+
public boolean validPalindrome(String s) {
29+
for(int i = 0, j = s.length() - 1; i < j;){
30+
if(s.charAt(i) == s.charAt(j)){
31+
i++; j--;
32+
} else {
33+
return isPaliandrome(s.substring(i, j)) || isPaliandrome(s.substring(i + 1, j + 1));
34+
}
35+
}
36+
return true;
37+
}
38+
39+
private boolean isPaliandrome(String s){
40+
for(int i = 0, j = s.length() - 1; i < j;){
41+
if(s.charAt(i) == s.charAt(j)){
42+
i++; j--;
43+
} else return false;
44+
}
45+
return true;
46+
}
47+
}

0 commit comments

Comments
 (0)