去除重复字符,并保证最小字典序

要求去除重复字符,且不能打乱顺序,实现最小字典序
我的思路是:
1、把字符串转为单个字符的列表
2、统计每个字符出现的次数
3、将相邻的字符比较,如果str[i]>=str[i+1],且srt[i]字符出现的个数大于等于2。则这个字符是应该去掉的。每轮去重后,重新给str赋值去重后的字符数组。
4.考虑到重复字符,应该使用while多次进行第3的操作,直到map的大小和字符串长度相等,则说明没有重复的字符了,停止循环。
import java.util.LinkedHashMap;

public class test {
    public static void main(String[] args) {

        //这里为第1.分割字符串
        String[] str = "bcbcacac".split("");  

        //这里为第2.统计字符个数
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        for(String s : str){
            map.put(s, map.getOrDefault(s, 0) + 1);
        }

        for(String key : map.keySet()){
            System.out.println(key + " " + map.get(key));
        }

        String newstr = "";
        boolean flag = true;

        while (flag) {
            for (int i = 0; i < str.length - 1; i++) {

            //这里为第3.去重操作
                if (str[i].compareTo(str[i + 1]) >= 0 && map.get(str[i]) >= 2) {
                    map.put(str[i], map.get(str[i]) - 1);
                    str[i] = null;
                } else {
                    newstr = newstr + str[i];
                }
            }
            if(map.get(str[str.length-1]) == 1) {
                newstr = newstr + str[str.length - 1];
            }

            str = newstr.split("");
            newstr = "";

            if(map.size()==str.length){
                flag = false;
            }
        }

        for(String s : str) {
            System.out.println(s);
        }
    }
}

例:

输入:bcbcacac   应输出:bac

力扣测试上也成功通过!

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是解题思路: 首先,我们可以统计每个字符出现的次数,然后遍历字符串中的每个字符。对于每个字符,如果它未被访问过,我们就将它与栈顶元素进行比较,如果栈顶元素比它大并且后面还有栈顶元素,那么我们就可以将栈顶元素出栈,直到栈为空或者栈顶元素比当前字符小为止。最后将当前字符入栈,并标记它已经被访问过。这样就可以保证最终得到的结果中每个字母只出现一次,并且字典序最小。 以下是代码实现: ```c++ #include <iostream> #include <cstring> using namespace std; string removeDuplicateLetters(string s) { int cnt[26] = {0}; // 统计每个字符出现的次数 bool vis[26] = {false}; // 标记每个字符是否在栈中 char stack[1001]; // 模拟栈 int top = -1; // 栈顶指针 for (int i = 0; i < s.size(); i++) { cnt[s[i] - 'a']++; } for (int i = 0; i < s.size(); i++) { int idx = s[i] - 'a'; if (!vis[idx]) { while (top >= 0 && stack[top] > s[i] && cnt[stack[top] - 'a'] > 0) { vis[stack[top] - 'a'] = false; top--; } stack[++top] = s[i]; vis[idx] = true; } cnt[idx]--; } string res = ""; for (int i = 0; i <= top; i++) { res += stack[i]; } return res; } int main() { string s; cin >> s; cout << removeDuplicateLetters(s) << endl; return 0; } ``` 时间复杂度:$O(n^2)$,由于内层while循环的时间复杂度是$O(n)$,而外层for循环需要执行n次,所以总的时间复杂度是$O(n^2)$。 空间复杂度:$O(n)$,由于栈的大小最大为字符串长度n,所以空间复杂度为$O(n)$。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值