-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOther.java
66 lines (55 loc) · 1.73 KB
/
Other.java
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
package Stack;
public class Other {
static String lexicoMaxSubsequence(String s, int n)
{
Stack<Character> st = new Stack<Character>();
// Stores if any alphabet is present
// in the current stack
int[] visited = new int[26];
int[] cnt = new int[26];
for (int i = 0; i < 26; i++) {
visited[i] = 0;
cnt[i] = 0;
}
// Findthe number of occurrences of
// the character s[i]
for (int i = 0; i < n; i++) {
cnt[s.charAt(i) - 'a']++;
}
for (int i = 0; i < n; i++) {
// Decrease the character count
// in remaining string
cnt[s.charAt(i) - 'a']--;
// If character is already present
// in the stack
if (visited[s.charAt(i) - 'a'] > 0) {
continue;
}
// if current character is greater
// than last character in stack
// then pop the top character
while (!st.empty() && st.peek() < s.charAt(i)
&& cnt[st.peek() - 'a'] != 0) {
visited[st.peek() - 'a'] = 0;
st.pop();
}
// Push the current character
st.push(s.charAt(i));
visited[s.charAt(i) - 'a'] = 1;
}
// Stores the resultant string
String s1 = "";
// Generate the string
while (!st.empty()) {
s1 = st.peek() + s1;
st.pop();
}
// Return the resultant string
return s1;
}
public static void main(String[] args) {
String S = "ababc";
int N = S.length();
System.out.println(lexicoMaxSubsequence(S, N));
}
}