Skip to content

Commit 8881a62

Browse files
Update 0647-palindromic-substrings.java
Made the code more concise and readable.
1 parent 6e1801d commit 8881a62

File tree

1 file changed

+20
-29
lines changed

1 file changed

+20
-29
lines changed

java/0647-palindromic-substrings.java

Lines changed: 20 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,26 @@
11
class Solution {
2-
32
public int countSubstrings(String s) {
4-
if (s.length() < 2) {
5-
return s.length();
6-
}
7-
int result = 0;
3+
int res = 0;
4+
85
for (int i = 0; i < s.length(); i++) {
9-
// Odd Length
10-
int left = i, right = i;
11-
while (
12-
left >= 0 &&
13-
right < s.length() &&
14-
s.charAt(left) == s.charAt(right)
15-
) {
16-
result++;
17-
left--;
18-
right++;
19-
}
20-
// Even Length
21-
left = i;
22-
right = i + 1;
23-
while (
24-
left >= 0 &&
25-
right < s.length() &&
26-
s.charAt(left) == s.charAt(right)
27-
) {
28-
result++;
29-
left--;
30-
right++;
31-
}
6+
res += countSubstrings(s, i, i);
7+
res += countSubstrings(s, i, i + 1);
8+
}
9+
10+
return res;
11+
}
12+
13+
public int countSubstrings(String s,
14+
int start, int end) {
15+
int res = 0;
16+
17+
while (start >= 0 && end < s.length()
18+
&& s.charAt(start) == s.charAt(end)) {
19+
++res;
20+
--start;
21+
++end;
3222
}
33-
return result;
23+
24+
return res;
3425
}
3526
}

0 commit comments

Comments
 (0)