File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int countSubstrings (String s ) {
3
+ /**
4
+ * time complexity: O(n);
5
+ * space complexity: O(1);
6
+ */
7
+
8
+ int output = 0 ;
9
+ // ex) abc
10
+ // 1. abc
11
+ // 2. bc
12
+ // 3. c
13
+ for (int i = 0 ; i < s .length (); i ++) {
14
+ output += palindromicCheck (s .substring (i , s .length ()));
15
+ }
16
+ return output ;
17
+ }
18
+
19
+ public int palindromicCheck (String str ) {
20
+ int result = 0 ;
21
+ /**
22
+ * ex) abc
23
+ * 1. a
24
+ * 2. ab
25
+ * 3. abc
26
+ */
27
+ for (int i = 0 ; i < str .length (); i ++) {
28
+ String candidate = str .substring (0 , i +1 );
29
+ if (palindromic (candidate )) {
30
+ result += 1 ;
31
+ }
32
+ }
33
+ return result ;
34
+ }
35
+
36
+ public boolean palindromic (String candidate ) {
37
+ int start = 0 ;
38
+ int end = candidate .length () - 1 ;
39
+
40
+ /** ex)abc
41
+ * 1. a -> true
42
+ * 2. ab -> false
43
+ * 3. abc -> false
44
+ */
45
+ while (start < end ) {
46
+ if (candidate .charAt (start ) != candidate .charAt (end )) return false ;
47
+ start += 1 ;
48
+ end -= 1 ;
49
+ }
50
+ return true ;
51
+ }
52
+ }
You can’t perform that action at this time.
0 commit comments