Leetcode--Java--1081. 不同字符的最小子序列

题目描述

返回 s 字典序最小的子序列,该子序列包含 s 的所有不同字符,且只包含一次。

样例描述

示例 1:

输入:s = "bcabc"
输出:"abc"
示例 2:

输入:s = "cbacdcbc"
输出:"acdb"

思路

本题与这题完全一样,只是说法不同

代码

class Solution {
    
    
    public String removeDuplicateLetters(String s) {
    
    
       String res = "";
       boolean inRes[] = new boolean[26]; //是否在答案中出现过
       int lastPos[] = new int[26]; //最后出现的位置
       int n = s.length();
       for (int i = 0; i < n; i ++ ) {
    
    
           lastPos[s.charAt(i) - 'a'] = i;
       }
       for (int i = 0; i < n; i ++ ) {
    
    
           char c = s.charAt(i);
           if (inRes[c - 'a']) continue;
           while (!"".equals(res) && res.charAt(res.length() - 1) > c && lastPos[res.charAt(res.length() - 1) - 'a'] > i) {
    
    
               //标记为没出现过
              inRes[res.charAt(res.length() - 1) - 'a'] = false;
              //去掉最后一位字符
              res = res.substring(0, res.length() - 1);
           }
           //加入新的字符,并且标记为出现过
           res += c;
           inRes[c - 'a'] = true;
       }
       return res;
    }
}

Guess you like

Origin blog.csdn.net/Sherlock_Obama/article/details/121742947