这题是豌豆荚二面的一个算法题,和leetcode的某些题目类似。其思路是这样的
返回子字符串[start:end
你会发现[start:end]为待求字符串。可以在纸上画画看
class Solution {
String getShortestSubString(String str) {
if (str == null || str.length() <= 1) {
return str;
}
// 记录目标字符串的起始索引
int start = 0, end = str.length() - 1;
// 记录目标字符串的开始位置
int pStart = 0;
Map<Character, List<Integer>> map = new HashMap<Character, List<Integer>>();
for (int index = 0; index < str.length(); index++) {
map.put(str.charAt(index), null);
}
int remainingCharacter = map.keySet().size();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (map.get(c) == null) {
List list = new LinkedList<Integer>();
map.put(c, list);
remainingCharacter--;
}
map.get(c).add(i);
while (map.get(str.charAt(pStart)).size() > 1) {
map.get(str.charAt(pStart)).remove(0);
pStart++;
}
if (remainingCharacter == 0) {
if (i - pStart < end - start) {
start = pStart;
end = i;
}
}
}
return str.substring(start, end + 1);
}
}
class TestSolution {
@Test
public void testGetShortestSubString() {
Solution solution = new Solution();
Assert.assertEquals("dbccaaabcefg", solution.getShortestSubString("abcddbccaaabcefggf"));
}
}
原文地址:http://blog.csdn.net/jiewuyou/article/details/45061971