Maximize Number of Subsequences in a String LeetCode solution in Java

1
class Solution {
2
public long maximumSubsequenceCount(String text, String pattern) {
3
// when pattern[0] == pattern[1]
4
if (pattern.charAt(0) == pattern.charAt(1)) {
5
long freq = 1;
6
// O(N)
7
for (int i = 0; i < text.length(); i++) {
8
if (text.charAt(i) == pattern.charAt(0)) {
9
freq++;
10
}
11
}
12
// number of subsequences : choose any two characters from freq nC2
13
return (freq * (freq - 1)) / 2;
14
}
15

16
// choice 1
17
String text1 = pattern.charAt(0) + text;
18

19
int freq = 0;
20
long count1 = 0;
21
// O(N)
22
for (int i = 0; i < text1.length(); i++) {
23
if (text1.charAt(i) == pattern.charAt(0)) {
24
freq++;
25
} else if (text1.charAt(i) == pattern.charAt(1)) {
26
count1 += freq;
27
}
28
}
29

30
// choice 2
31
String text2 = text + pattern.charAt(1);
32
freq = 0;
33
long count2 = 0;
34
// O(N)
35
for (int i = text2.length() - 1; i >= 0; i--) {
36
if (text2.charAt(i) == pattern.charAt(1)) {
37
freq++;
38
} else if (text2.charAt(i) == pattern.charAt(0)) {
39
count2 += freq;
40
}
41
}
42

43
return Math.max(count1, count2);
44
}
45
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0