标签:
题目:
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"
解题思路:
此题的思路就是要删掉所有重复的字母,最后留下来的数列的字母组成都是唯一的,而且要尽量把字母值小的排在前面。
可以先遍历数组,把所有的字母和其出现的index value发到Map里。
"bcabc" -> ‘a‘ => 2; ‘b‘ =>0,3; ‘c‘ =>1,4
首先找到每个字母最小的index, 首先是a, 它的index是2, 然后b,c,的最外面的index3,4,都大于2。
把a之前的字母都删掉,这要map里就变成乐,‘b‘ => 3, ‘c‘ =>4
依次类推,知道map 的size 是空的。
JAVA代码:
28ms
public String removeDuplicateLetters(String s) { Map<Character, List<Integer>> map = new HashMap<Character, List<Integer>>(); if(s == null || s.length() <=1) return s; int len = s.length(); List<Character> keys = new ArrayList<Character>(); for(int i = 0; i < len; i++){ char c = s.charAt(i); List<Integer> list = null; if(map.containsKey(c)){ list = map.get(c); }else{ list = new ArrayList<Integer>(); keys.add(c); } list.add(i); map.put(c, list); } Collections.sort(keys); StringBuilder sb = new StringBuilder(); while(!map.isEmpty()){ boolean found = true; for(int j = 0; j < keys.size(); j++){ char cur = keys.get(j); int curIndex = map.get(cur).get(0); for(int n = 0; n < keys.size(); n++){ List<Integer> curList = map.get(keys.get(n)); if(curList.get(curList.size()-1) < curIndex){ found = false; break; } } if(found){ sb.append(cur); map.remove(cur); keys.remove(j); for(int m = 0; m < keys.size(); m++){ char temp = keys.get(m); List<Integer> tempList = map.get(temp); Iterator<Integer> it = tempList.iterator(); while(it.hasNext()){ Integer val = it.next(); if(val < curIndex){ it.remove(); } } } break; } found = true; } } return sb.toString(); }
[LeetCode]: Remove Duplicate Letters
标签:
原文地址:http://www.cnblogs.com/shuaticincin/p/5080319.html