• Leetcode 316.去除重复字母


    去除重复字母

    给定一个仅包含小写字母的字符串,去除字符串中重复的字母,使得每个字母只出现一次。需保证返回结果的字典序最小(要求不能打乱其他字符的相对位置)。

    示例 1:

    输入: "bcabc"

    输出: "abc"

    示例 2:

    输入: "cbacdcbc"

    输出: "acdb"

    Given the string s, the greedy choice (i.e., the leftmost letter in the answer) is the smallest s[i], s.t. the suffix s[i .. ] contains all the unique letters. (Note that, when there are more than one smallest s[i]'s, we choose the leftmost one. Why? Simply consider the example: "abcacb".)

    After determining the greedy choice s[i], we get a new string s' from s by

    removing all letters to the left of s[i],

    removing all s[i]'s from s.

    We then recursively solve the problem w.r.t. s'.

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

     1 public class Solution{
     2     public String removeDuplicateLetters(String s){
     3         int[] cnt=new int[26];
     4         int pos=0;
     5         for(int i=0;i<s.length();i++) cnt[s.charAt(i)-'a']++;
     6         for(int i=0;i<s.length();i++){
     7             if(s.charAt(i)<s.charAt(pos)){
     8                 pos=i;
     9             }
    10             if(--cnt[s.charAt(i)-'a']==0){
    11                 break;
    12             }
    13         }
    14         return s.length()==0?"":s.charAt(pos)+removeDuplicateLetters(s.substring(pos+1).replaceAll(""+s.charAt(pos),""));
    15     }
    16 }
  • 相关阅读:
    顺序表和链表优缺点
    指针和引用
    常见操作系统面试题
    网络套接字编程(UDP)
    Windows下的问题
    解决虚拟机选择桥接模式连不上网(CentOs6.5)
    DevOps平台实践
    Prometheus实现k8s集群的服务监控
    Kubernetes集群的日志EFK解决方案
    Helm
  • 原文地址:https://www.cnblogs.com/kexinxin/p/10235182.html
Copyright © 2020-2023  润新知