-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path316.remove-duplicate-letters.java
More file actions
49 lines (42 loc) · 1.89 KB
/
Copy path316.remove-duplicate-letters.java
File metadata and controls
49 lines (42 loc) · 1.89 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
class Solution {
public String removeDuplicateLetters(String s) {
//character frequency
int[] count = new int[26];
for(char c : s.toCharArray()){
count[c-'a']++;
}
//to keep track of visited character so that we don't use them if present in answer
boolean[] visited = new boolean[26];
//Stack store resulting characters
Stack<Character> stack = new Stack<>();
//traverse through string and add characters
for(char c : s.toCharArray()){
//dcrement the frequncy of character since we are using it in answer
//!!! We have decrement the character frequncy before checking it is visited
count[c - 'a']--;
//if already present in tstack we dont need the character
if(visited[c - 'a']){
continue;
}
//traverse through the stack and check for larger characters
//if found and it is not the last position then pop from stack
//Eg: bcabc => if stack has bc, now a<b and curr b is not the last one
//if not in last position come out of loop and add curr character to stack
while(!stack.isEmpty() && c < stack.peek() && count[stack.peek() - 'a'] > 0){
//make the current character available for next operations
visited[stack.pop() - 'a'] = false;
}
//add curr charatcer to string
stack.push(c);
//mark it as vistied
visited[c - 'a'] = true;
}
//Now characters are in reverse order in stack
//Use StringBuilder instead of String for storing result
StringBuilder sb = new StringBuilder();
while(!stack.isEmpty()){
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}