【LeetCode】316. Remove Duplicate Letters 去除重复字母(Medium)(JAVA)
题目地址: https://leetcode.com/problems/remove-duplicate-letters/
题目描述:
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.
Note: This question is the same as 1081: https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/
Example 1:
Input: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
Constraints:
- 1 <= s.length <= 10^4
- s consists of lowercase English letters.
题目大意
给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
解题方法
- 找出第一个字符:先把所有字符的出现次数用一个 count 数组记录下来
- 然后再从头开始遍历,记录下当前位置之前最小的字符的位置 min ,每次遍历过 count–,知道当前 count[k] == 0,说明这个字符后面没有了,也就是这个字符必须放在这之前,不能再被去除了
- min 位置就是第一个要找出的字符,min 之前的都没有了,之后只需要 min 往后找即可,而且 min 位置的字符也不需要再找了
class Solution {
public String removeDuplicateLetters(String s) {
if (s.length() <= 1) return s;
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
count[s.charAt(i) - 'a']++;
}
int min = 0;
for (int i = 0; i < s.length(); i++) {
char temp = s.charAt(i);
if (temp < s.charAt(min)) min = i;
count[temp - 'a']--;
if (count[temp - 'a'] == 0) break;
}
return s.charAt(min) + removeDuplicateLetters(s.substring(min + 1).replaceAll("" + s.charAt(min), ""));
}
}
执行耗时:30 ms,击败了5.43% 的Java用户
内存消耗:39.4 MB,击败了6.07% 的Java用户