Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions longest-repeating-character-replacement/njngwn.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Time Complexity: O(n), n: s.length()
// Space Complexity: O(1)
class Solution {
public int characterReplacement(String s, int k) {
int[] charFreqArr = new int[26]; // s consists of only uppercase English letters
int maxFreq = 0;
int maxLength = 0;

for (int left = 0, right = 0; right < s.length(); right++) {
char letter = s.charAt(right);
int letterIdx = letter-'A';

charFreqArr[letterIdx]++;
maxFreq = Math.max(maxFreq, charFreqArr[letterIdx]);

// when left idx moves rightward? -> k + maxFreq < size of sliding window
// here, we don't neet to recalculate maxFreq because the point is to calculate 'best' maxFreq
if (maxFreq + k < right-left+1) {
char leftChar = s.charAt(left);
charFreqArr[leftChar-'A']--;
left++;
}

maxLength = Math.max(maxLength, right-left+1);
}

return maxLength;
}
}

// AABABBA, k=1, maxFreq=1, maxLength=1
// l
// r

// AABABBA, k=1, maxFreq=2, maxLength=2
// lr

// AABABBA, k=1, maxFreq=2, maxLength=3
// l r

// AABABBA, k=1, maxFreq=3, maxLength=4
// l r

// AABABBA, k=1, maxFreq=3, maxLength=4 ==> fail
// l r

// AABABBA, k=1, maxFreq=3
// l r
36 changes: 36 additions & 0 deletions palindromic-substrings/njngwn.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Time Complexity: O(n*n), n: s.length()
// Space Complexity: O(1)
class Solution {
public int countSubstrings(String s) {
int cnt = 0;

for (int i = 0; i < s.length(); i++, cnt++) { // i: center of palindrom
// odd number palindrom: e.g. aba
int left = i-1, right = i+1;

while (left >= 0 && right < s.length()) {
if (s.charAt(left) != s.charAt(right)) {
break;
}
cnt++;
left--;
right++;
}
Comment on lines +11 to +18
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

해당 부분을 메소드화 하셔서 odd, even 을 각각 boolean으로 확인하시면 중복 코드를 줄이실 수 있을것 같아요!


// even number palindrom: e.g. abba
left = i;
right = i+1;

while (left >= 0 && right < s.length()) {
if (s.charAt(left) != s.charAt(right)) {
break;
}
cnt++;
left--;
right++;
}
}

return cnt;
}
}