算法

LeetCode316. 去除重复字母

2021-08-30  本文已影响0人  Timmy_zzh
1.题目描述
示例 1:
输入:s = "bcabc"
输出:"abc"
  
示例 2:
输入:s = "cbacdcbc"
输出:"acdb"
 
提示:
1 <= s.length <= 104
s 由小写英文字母组成
2.解题思路:
    public String removeDuplicateLetters_v1(String s) {
        if (s.length() <= 1) {
            return s;
        }
        char[] chars = s.toCharArray();
        int len = chars.length;
        int[] letters = new int[26];
        //1。先保存字符串中字母在数组中最后出现的位置
        for (int i = 0; i < len; i++) {
            char ch = chars[i];
            letters[ch - 'a'] = i;
        }

        //2.在字母最后出现的位置前,找到字典序最小的字母位置
        int pos = 0;
        for (int i = 0; i < len; i++) {
            char ch = chars[i];
            //找到
            if (chars[pos] > ch) {
                pos = i;
            }
            if (letters[ch - 'a'] == i) {
                break;
            }
        }

        //3.找到最小字母,并进行截取后面的字母
        char litter = chars[pos];
        String remain = s.substring(pos + 1);
        //将最小字母剔除
        remain = remain.replaceAll("" + litter, "");
        return litter + removeDuplicateLetters_v1(remain);
    }
    public String removeDuplicateLetters(String s) {
        System.out.println(s);
        int[] letters = new int[26];
        boolean[] box = new boolean[26];

        Stack<Character> stack = new Stack<>();
        char[] chars = s.toCharArray();
        int len = chars.length;
        for (int i = 0; i < len; i++) {
            letters[chars[i] - 'a'] = i;
        }
        for (int i = 0; i < len; i++) {
            char ch = chars[i];
            if (!box[ch - 'a']) {  //当前字母没有在栈中
                //与栈顶元素进行比较,判断是否需要删除栈顶元素
                while (!stack.isEmpty() && stack.peek() > ch && letters[stack.peek() - 'a'] > i) {
                    Character pop = stack.pop();
                    box[pop - 'a'] = false;
                }
                stack.push(ch);
                box[ch - 'a'] = true;
            }
        }
        String res = "";
        while (!stack.isEmpty()) {
            res = stack.pop() + res;
        }
        return res;
    }
3.总结
上一篇下一篇

猜你喜欢

热点阅读