1. 程式人生 > 其它 >【LeetCode】316. Remove Duplicate Letters 去除重複字母(Medium)(JAVA)

【LeetCode】316. Remove Duplicate Letters 去除重複字母(Medium)(JAVA)

技術標籤:Leetcodeleetcodejava演算法字串動態規劃

【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 相同

解題方法

  1. 找出第一個字元:先把所有字元的出現次數用一個 count 陣列記錄下來
  2. 然後再從頭開始遍歷,記錄下當前位置之前最小的字元的位置 min ,每次遍歷過 count–,知道當前 count[k] == 0,說明這個字元後面沒有了,也就是這個字元必須放在這之前,不能再被去除了
  3. 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使用者

歡迎關注我的公眾號,LeetCode 每日一題更新