-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay21.java
More file actions
77 lines (65 loc) · 1.8 KB
/
Copy pathDay21.java
File metadata and controls
77 lines (65 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Problem:Substrings with K distinct
// https://bit.ly/3CfQfYi
class Solution {
int countSubstr(String s, int k) {
return count(s, k) - count(s, k - 1);
}
private int count(String s, int k) {
int left = 0, right = 0, count = 0, distinctCount = 0;
int[] freq = new int[256];
while (right < s.length()) {
if (freq[s.charAt(right)] == 0) {
distinctCount++;
}
freq[s.charAt(right)]++;
while (distinctCount > k) {
freq[s.charAt(left)]--;
if (freq[s.charAt(left)] == 0) {
distinctCount--;
}
left++;
}
count += right - left + 1;
right++;
}
return count;
}
}
//TC:O(N)
//SC:O(1)
//Problem:Longest Palindromic Substring
//https://leetcode.com/problems/longest-palindromic-substring/description/
class Solution {
public String longestPalindrome(String str) {
if (str.length() <= 1)
return str;
String LPS = "";
for (int i = 1; i < str.length(); i++) {
int low = i;
int high = i;
while(str.charAt(low) == str.charAt(high)) { //odd len
low--;
high++;
if (low == -1 || high == str.length())
break;
}
String palindrome = str.substring(low+1, high);
if (palindrome.length() > LPS.length()) {
LPS = palindrome;
}
low = i-1; //even len
high = i;
while(str.charAt(low) == str.charAt(high)) {
low--;
high++;
if (low == -1 || high == str.length())
break;
}
palindrome = str.substring(low+1, high);
if (palindrome.length() > LPS.length()) {
LPS = palindrome;
}
}
return LPS;
}
}