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"

    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), ""));
    
        }
    }
  • 相关阅读:
    加分二叉树
    飞扬的小鸟
    洛谷P2066 机器分配
    解方程
    洛谷P1781 宇宙总统
    洛谷P1311 选择客栈
    洛谷P1081 开车旅行70分
    CSS清除浮动
    常见的内联元素与块状元素
    标签的权值问题(优先级)
  • 原文地址:https://www.cnblogs.com/joannacode/p/6132579.html
Copyright © 2011-2022 走看看