首页 > 其他 > 详细

316. Remove Duplicate Letters

时间:2016-12-05 07:45:21      阅读:220      评论:0      收藏:0      [点我收藏+]

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"

The runtime is O(26 * n) = O(n).

public class Solution {
        // 形成字典 int[26]
        //找到当前str中最小的值 或者为 cnt为1的char
        //recursive: remove min 前面所有的char 然后将s中所有的charAt(min) 的字符移除;
    public String removeDuplicateLetters(String s) {
        int[] count = new int[26];
        int min = 0;
        for(int i = 0 ; i < s.length() ; i++){
            count[s.charAt(i) - ‘a‘] ++;
        }
        for(int i = 0 ; i < s.length(); i++){
            if(s.charAt(i) < s.charAt(min)) min = i;
            if(--count[s.charAt(i) - ‘a‘]  == 0) break;
        }
        return s.length()==0 ? "" : s.charAt(min) + removeDuplicateLetters(s.substring(min+1).replaceAll(""+s.charAt(min), ""));

    }
}

 

316. Remove Duplicate Letters

原文:http://www.cnblogs.com/joannacode/p/6132579.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!