forked from prateekshyap/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CheckPalindrome2.java
57 lines (52 loc) · 1.34 KB
/
CheckPalindrome2.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
/*https://leetcode.com/problems/valid-palindrome-ii/*/
class Solution {
public boolean validPalindrome(String s) {
//check if already palindrome
StringBuffer buffer = new StringBuffer(s);
int i = 0, j = s.length()-1, k = 0, l = 0;
boolean flag = true;
while (i <= j)
{
if (buffer.charAt(i) != buffer.charAt(j))
{
flag = false;
break;
}
++i; --j;
}
if (flag) return true;
//delete the first mismatch and check
buffer.delete(i,i+1);
flag = true;
k = 0;
l = buffer.length()-1;
while (k <= l)
{
if (buffer.charAt(k) != buffer.charAt(l))
{
flag = false;
break;
}
++k; --l;
}
if (flag) return true;
//delete the second mismatch and check
buffer = new StringBuffer(s);
buffer.delete(j,j+1);
flag = true;
k = 0;
l = buffer.length()-1;
while (k <= l)
{
if (buffer.charAt(k) != buffer.charAt(l))
{
flag = false;
break;
}
++k; --l;
}
if (flag) return true;
//return false at the end
return false;
}
}