1+
2+
3+ class Solution {
4+
5+ public int countSubstrings (String s ) {
6+ int n = s .length ();
7+ int count = 0 ;
8+
9+ // ํ์์ ์ง์ ํตํฉ ์ฒ๋ฆฌ (0๋ถํฐ 2n-1๊น์ง)
10+ for (int center = 0 ; center < 2 * n - 1 ; center ++) {
11+ int left = center / 2 ;
12+ int right = left + center % 2 ;
13+
14+ while (left >= 0 && right < n && s .charAt (left ) == s .charAt (right )) {
15+ count ++;
16+ left --;
17+ right ++;
18+ }
19+ }
20+
21+ return count ;
22+ }
23+
24+ // ๋ ๊ฐ๋
์ฑ์ด ์ข์ ํ์ด
25+
26+ /**
27+ * 1. ํ๋ฌธ์ ์ค์ฌ์ ๋ช
ํํ๊ฒ ๋ถ๋ฆฌํ๋ค.
28+ * 2. c๋ ํ๋ฌธ์ ์ค์ฌํ๋ณด๊ฐ ๋๋ค. 1๊ธ์์ง๋ฆฌ ์ค์ฌ์ด๊ฑฐ๋ ํน์ ๋ ๊ธ์์ง๋ฆฌ ํ๋ฌธ์ ์ผ์ชฝ ์ค์ฌ์ด๋ค.
29+ * 3. c๋ฅผ ํ์ ๊ธธ์ด ํ๋ฌธ์ ์ค์ฌ์ผ๋ก ์ค์ ํ๋ค -> expand(s,c,c)
30+ * 4. c๋ถํฐ c+1๊น์ง ์ง์ ๊ธธ์ด ํ๋ฌธ์ ์ผ์ชฝ ์ค์ฌ์ผ๋ก ์ค์ ํ๋ค -> expand(s,c,c+1)
31+ *
32+ * ์ด๋ ๊ฒ ํ๋ ์ด์ ๋ ABA์ ABBA ๋ ๊ฐ์ง ๊ฒฝ์ฐ๋ฅผ ๋ชจ๋ ์ปค๋ฒํ๊ธฐ ์ํด์์ด๋ค.
33+ */
34+ public int countSubstrings2 (String s ) {
35+ int n = s .length ();
36+ int count = 0 ;
37+ for (int c = 0 ; c < n ; c ++) {
38+ count += expand (s , c , c ); // ํ์ ๊ธธ์ด ์ค์ฌ
39+ count += expand (s , c , c + 1 ); // ์ง์ ๊ธธ์ด ์ค์ฌ
40+ }
41+ return count ;
42+ }
43+
44+ private int expand (String s , int L , int R ) {
45+ int add = 0 ;
46+ while (L >= 0 && R < s .length () && s .charAt (L ) == s .charAt (R )) {
47+ add ++;
48+ L --;
49+ R ++;
50+ }
51+ return add ;
52+ }
53+
54+ /**
55+ * ํ๋ผ์ด๋น ๋ฉ์๋ "ํ์ฅ" ์ ์ธ
56+ * 1. L, R ํฌ์ธํฐ ์ธ๋ฑ์ค๋ฅผ ๋ฐ๋๋ค.
57+ * 2. ๋ ํฌ์ธํฐ๊ฐ ๋ฌธ์์ด ๋ด ์ ํจํ ๋ฒ์์ ์์ด์ผ ํ๋ค.
58+ * 3. L๊ณผ R์ด ๊ฐ๋ฆฌํค๋ ๋ฌธ์๊ฐ ๊ฐ์์ผ ํ๋ค.
59+ * 2์ 3์ ๋ชจ๋ ๋ง์กฑํ๋ค๋ฉด ํ๋ฌธ
60+ */
61+
62+ }
0 commit comments