zoukankan      html  css  js  c++  java
  • 316. Remove Duplicate Letters

    Given a string which contains only lowercase letters, remove duplicate letters so that every letter appear once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.

    Example:

    Given "bcabc"
    Return "abc"

    Given "cbacdcbc"
    Return "acdb"

    Credits:
    Special thanks to @dietpepsi for adding this problem and creating all test cases.


    根据字符串大小排序:优先把最小的字符放在前面,这样生成的字符肯定最小。问题是如何找出可以放在第一的最小字符呢?
         首先,找出s中出现的所有字符最后一次出现的位置,再从中找到最小的位置index1,从0到index1中找到最小字符,把选出来的字符做好标记
             我们可以选从0到index中的任意一个字符。其他所有待选字符都还在index-end中,等待之后选。
         然后在剩余待选字符中找到最后一次出现位置的最小值index2,再从index1+1 到index2里找出最小字符,把选出来的字符做好标记
         重复…

    时间复杂度O(n)

    public class Solution {
        public String removeDuplicateLetters(String s) {
            int[] index = new int[26];
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.length(); i++) {
                index[s.charAt(i) - 'a'] = i + 1;
            }
            int start = 0;
            int cur = findMinIndex(index); // Return the index of the characters' last occurance in the string
            while (cur >= 0) {
                int chosen = findMinChar(s, start, cur, index); // Find the index of the smallest char from 0 to 'cur' in the string
                start = chosen + 1;
                index[s.charAt(chosen) - 'a'] = 0;
                sb.append(s.charAt(chosen));
                cur = findMinIndex(index);
            }
            return sb.toString();
            
        }
        private int findMinIndex(int[] index) {
            int min = Integer.MAX_VALUE;
            for (int i = 0; i < 26; i++) {
                if (index[i] > 0 && min > index[i]) {
                    min = index[i];
                }
            }
            if (min == Integer.MAX_VALUE) {
                return -1;
            } else {
                return min - 1;
            }
        }
        private int findMinChar(String s, int start, int end, int[] index) {
            int min = -1;
            char c = '{';
            for (int i = start; i <= end; i++) {
                if (index[s.charAt(i) - 'a'] > 0 && c > s.charAt(i)) {
                    c = s.charAt(i);
                    min = i;
                }
            }
            return min;
        }
    }
    
  • 相关阅读:
    JB开发之二 [jailbreak,越狱开发研究]
    iOS9 Https技术预研
    Tweak和app交互方案【进程通信】
    iOS设备抓包终极解决方案(支持https)
    Anti-Anti dylib(反 反-dylib钩子(Anti-tweak))
    Hook ptrace 调试加入了ptrace函数的程序
    How do I determine if I'm being run under the debugger?
    个人整理的一些iOS Entitlements
    SQLite在多线程环境下的应用
    别的程序员是怎么读你的简历的
  • 原文地址:https://www.cnblogs.com/yuchenkit/p/7169500.html
Copyright © 2011-2022 走看看