[leetcode]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"

这题应该是用贪心算法的了,然后利用栈做数据结构就行了.

 

package leetcode.RemoveDumplicateLetters316;

import java.util.Stack;

public class Solution {

    public String removeDuplicateLetters( String s ) {
        StringBuilder ret = new StringBuilder();
        if( s == null || s.length() < 1 )
            return ret.toString();
        Stack<Character> stack = new Stack<Character>();
        int[] f = new int[ 26 ];
        boolean[] b = new boolean[ 26 ];
//先统计各字母数的情况,已便后面做贪心时选择判断
for( int i = 0; i < s.length(); i++ ) { f[ s.charAt( i ) - 'a' ]++; } for( int i = 0; i < s.length(); i++ ) {
//只处理不在stack中的元素.
if( !b[ ( s.charAt( i ) - 'a' ) ] ) {
//这里是关键,做了贪心选择,加入发现有字典序列更小的元素,进行选择。
while( !stack.isEmpty() && s.charAt( i ) <= stack.peek() && f[ stack.peek() - 'a' ] >= 1 ) { b[ stack.peek() - 'a' ] = false; stack.pop(); }
//进栈
if( !b[ s.charAt( i ) - 'a' ] ) { b[ s.charAt( i ) - 'a' ] = true; stack.push( s.charAt( i ) ); } } f[ s.charAt( i ) - 'a' ]--; } while( !stack.isEmpty() ) { ret.append( stack.pop() ); } ret = ret.reverse(); return ret.toString(); } public static void main( String[] args ) { // TODO Auto-generated method stub Solution s = new Solution(); System.out.println( s.removeDuplicateLetters( "bbcaac" ) ); } }

 

你可能感兴趣的:([leetcode]Remove Duplicate Letters)