File tree Expand file tree Collapse file tree 3 files changed +84
-0
lines changed
longest-common-subsequence
longest-repeating-character-replacement Expand file tree Collapse file tree 3 files changed +84
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int longestCommonSubsequence (String text1 , String text2 ) {
3+ int n = text1 .length ();
4+ int m = text2 .length ();
5+
6+ int [][] dp = new int [n + 1 ][m + 1 ];
7+
8+ for (int i = 1 ; i <= n ; i ++) {
9+ for (int j = 1 ; j <= m ; j ++) {
10+ if (text1 .charAt (i - 1 ) == text2 .charAt (j - 1 )) {
11+ dp [i ][j ] = dp [i - 1 ][j - 1 ] + 1 ;
12+ } else {
13+ dp [i ][j ] = Math .max (dp [i - 1 ][j ], dp [i ][j - 1 ]);
14+ }
15+ }
16+ }
17+
18+ return dp [n ][m ];
19+ }
20+ }
21+ // Time Complexity: O(n * m)
22+ // Space Complexity: O(n * m)
Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int characterReplacement (String s , int k ) {
3+ int [] count = new int [26 ];
4+ int maxCount = 0 ;
5+ int left = 0 ;
6+ int result = 0 ;
7+
8+ for (int right = 0 ; right < s .length (); right ++) { // sliding window에서의 right pointer
9+ char currentChar = s .charAt (right );
10+ count [currentChar - 'A' ]++; // 현재 문자 카운트 증가
11+ maxCount = Math .max (maxCount , count [currentChar - 'A' ]);
12+
13+ while (right - left + 1 - maxCount > k ) { // 현재 window의 길이 - 가장 많이 등장한 문자 개수 > k
14+ // 윈도우 크기 - maxCount > k가 되면, k번의 변경으로는 모든 문자를 동일하게 만들 수 없다는 뜻이므로
15+ // 윈도우의 왼쪽 포인터(left)를 증가시켜 윈도우 크기를 줄인다.
16+ count [s .charAt (left ) - 'A' ]--; // left pointer의 문자 카운트 감소
17+ left ++;
18+ }
19+
20+ result = Math .max (result , right - left + 1 );
21+ }
22+
23+
24+ return result ;
25+ }
26+ }
27+ // Time Complexity: O(n)
28+ // Space Complexity: O(1)
Original file line number Diff line number Diff line change 1+ class Solution {
2+ public int countSubstrings (String s ) {
3+ int count = 0 ;
4+ int n = s .length ();
5+
6+ for (int center = 0 ; center < 2 * n - 1 ; center ++) {
7+ int left = center / 2 ;
8+ int right = left + (center % 2 ); // 홀/짝 팰린드롬 처리
9+
10+ while (left >= 0 && right < n && s .charAt (left ) == s .charAt (right )) {
11+ count ++;
12+ left --;
13+ right ++;
14+ }
15+ }
16+
17+ return count ;
18+ }
19+ }
20+ // Time Complexity: O(n^2)
21+ // Space Complexity: O(1)
22+
23+ /*
24+ 예시: "abc"
25+ 중심이 문자일 때:
26+ a (index 0),
27+ b (index 1),
28+ c (index 2)
29+ 중심이 문자 사이일 때:
30+ between a and b
31+ between b and c
32+ → 총 2 * 3 - 1 = 5개의 중심
33+ */
34+
You can’t perform that action at this time.
0 commit comments