zoukankan      html  css  js  c++  java
  • LeetCode 1081. Smallest Subsequence of Distinct Characters

    原题链接在这里:https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/

    题目:

    Return the lexicographically smallest subsequence of text that contains all the distinct characters of text exactly once.

    Example 1:

    Input: "cdadabcc"
    Output: "adbc"
    

    Example 2:

    Input: "abcd"
    Output: "abcd"
    

    Example 3:

    Input: "ecbacba"
    Output: "eacb"
    

    Example 4:

    Input: "leetcode"
    Output: "letcod"

    Note:

    1. 1 <= text.length <= 1000
    2. text consists of lowercase English letters.

    题解:

    Try to build the string greedily. Mark the last appearence of each char in text.

    For current char c, if it is not already added. Keep check the last added char. If it is bigger than current c and that bigger char last appearence is after current index, then it means that this bigger char could be added later.

    Pop it out and mark it as unused.

    Now this makes sure that the char in stack are as small as possible.

    Time Complexity: O(n). n = text.length().

    Space: O(1). size 26.

    AC Java:

     1 class Solution {
     2     public String smallestSubsequence(String text) {
     3         int [] last = new int[26];
     4         for(int i = 0; i<text.length(); i++){
     5             last[text.charAt(i)-'a'] = i;
     6         }
     7         
     8         Stack<Character> stk = new Stack<>();
     9         boolean [] used = new boolean[26];
    10         for(int i = 0; i<text.length(); i++){
    11             char c = text.charAt(i);
    12             if(used[c-'a']){
    13                 continue;
    14             }
    15             
    16             while(!stk.isEmpty() && stk.peek()>c && last[stk.peek()-'a']>i){
    17                 char top = stk.pop();
    18                 used[top-'a'] = false;
    19             }
    20             
    21             stk.push(c);
    22             used[c-'a'] = true;
    23         }
    24         
    25         StringBuilder sb = new StringBuilder();
    26         for(char c : stk){
    27             sb.append(c);
    28         }
    29         
    30         return sb.toString();
    31     }
    32 }

    类似Remove Duplicate Letters.

  • 相关阅读:
    Improve Your Study Habits
    js中的cookie的读写操作
    js中数组/字符串常用属性方法归纳
    前端的一些常用DOM和事件归纳
    关于scroll无法绑定的问题
    页面内锚点定位及跳转方法总结
    js共享onload事件
    JS获取终端屏幕、浏览窗口的相关信息
    jsonp跨域问题记录
    关于if/else if
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/11976305.html
Copyright © 2011-2022 走看看