Skip to content

Commit 51f67fc

Browse files
add 647
1 parent 5cbbbeb commit 51f67fc

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

src/main/java/com/fishercoder/solutions/_647.java

+28
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,32 @@ private int extendPalindrome(String s, int left, int right) {
2525
return count;
2626
}
2727
}
28+
29+
public static class Solution2 {
30+
/**
31+
* Simple brute force solution is accepted as well, although not ideal in terms of time complexity: O(n^2)
32+
*/
33+
public int countSubstrings(String s) {
34+
int result = 0;
35+
for (int i = 0; i < s.length(); i++) {
36+
for (int j = i + 1; j <= s.length(); j++) {
37+
if (isPal(s.substring(i, j))) {
38+
result++;
39+
}
40+
}
41+
}
42+
return result;
43+
}
44+
45+
private boolean isPal(String str) {
46+
int i = 0;
47+
int j = str.length() - 1;
48+
while (i < j) {
49+
if (str.charAt(i++) != str.charAt(j--)) {
50+
return false;
51+
}
52+
}
53+
return true;
54+
}
55+
}
2856
}

src/test/java/com/fishercoder/_647Test.java

+3
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,18 @@
88

99
public class _647Test {
1010
private static _647.Solution1 solution1;
11+
private static _647.Solution2 solution2;
1112

1213
@BeforeClass
1314
public static void setup() {
1415
solution1 = new _647.Solution1();
16+
solution2 = new _647.Solution2();
1517
}
1618

1719
@Test
1820
public void test1() {
1921
assertEquals(3, solution1.countSubstrings("abc"));
22+
assertEquals(3, solution2.countSubstrings("abc"));
2023
}
2124

2225
}

0 commit comments

Comments
 (0)