本文共 997 字,大约阅读时间需要 3 分钟。
给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
注意:该题与 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters 相同
示例 1:
输入:s = “bcabc” 输出:“abc”
示例 2:
输入:s = “cbacdcbc” 输出:“acdb”
提示:
1 <= s.length <= 104 s 由小写英文字母组成
解题思路:维护一个栈,维护顺序。
class Solution { public String removeDuplicateLetters(String s) { // 统计最后出现的索引 int[] dict = new int[26]; // 对字符串进行转换 char[] arr = s.toCharArray(); // 统计 for(int i=0;istack = new Stack<>(); // 对其遍历 for(int i=0;i arr[i]&&dict[stack.peek()-'a']>i){ Character temp = stack.pop(); visited[temp-'a'] = false; } //加入栈中 stack.push(arr[i]); visited[arr[i]-'a'] = true; } // 结果 StringBuilder sb = new StringBuilder(); while(!stack.isEmpty()){ sb.append(stack.pop()); } return sb.reverse().toString(); }}
转载地址:http://pbwdf.baihongyu.com/