Skip to content

Commit 974959b

Browse files
committed
October leetcoding challenge, week 2, Q 4
1 parent f8f7b09 commit 974959b

File tree

1 file changed

+69
-0
lines changed
  • ds-algorithms-competitive-programming/src/main/java/competitiveProgramming/leetcode/thirtyDaysLeetcodingChallenge/october/week2

1 file changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package competitiveProgramming.leetcode.thirtyDaysLeetcodingChallenge.october.week2;
2+
3+
4+
import java.util.Stack;
5+
6+
/*
7+
https://leetcode.com/explore/challenge/card/october-leetcoding-challenge/560/week-2-october-8th-october-14th/3491/
8+
9+
Remove Duplicate Letters
10+
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
11+
12+
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
13+
14+
15+
16+
Example 1:
17+
18+
Input: s = "bcabc"
19+
Output: "abc"
20+
Example 2:
21+
22+
Input: s = "cbacdcbc"
23+
Output: "acdb"
24+
25+
26+
Constraints:
27+
28+
1 <= s.length <= 104
29+
s consists of lowercase English letters.
30+
*/
31+
public class RemoveDuplicateLetters {
32+
public static void main(String[] args) {
33+
System.out.println(removeDuplicateLetters("bcabc"));
34+
System.out.println(removeDuplicateLetters("cbacdcbc"));
35+
}
36+
37+
38+
public static String removeDuplicateLetters(String sr) {
39+
40+
int[] res = new int[26]; //will contain number of occurences of character (i+'a')
41+
boolean[] visited = new boolean[26]; //will contain if character (i+'a') is present in current result Stack
42+
char[] ch = sr.toCharArray();
43+
for (char c : ch) { //count number of occurences of character
44+
res[c - 'a']++;
45+
}
46+
Stack<Character> st = new Stack<>(); // answer stack
47+
int index;
48+
for (char s : ch) {
49+
index = s - 'a';
50+
res[index]--; //decrement number of characters remaining in the string to be analysed
51+
if (visited[index]) //if character is already present in stack, dont bother
52+
continue;
53+
//if current character is smaller than last character in stack which occurs later in the string again
54+
//it can be removed and added later e.g stack = bc remaining string abc then a can pop b and then c
55+
while (!st.isEmpty() && s < st.peek() && res[st.peek() - 'a'] != 0) {
56+
visited[st.pop() - 'a'] = false;
57+
}
58+
st.push(s); //add current character and mark it as visited
59+
visited[index] = true;
60+
}
61+
62+
StringBuilder sb = new StringBuilder();
63+
//pop character from stack and build answer string from back
64+
while (!st.isEmpty()) {
65+
sb.insert(0, st.pop());
66+
}
67+
return sb.toString();
68+
}
69+
}

0 commit comments

Comments
 (0)