标签:style blog io ar java for sp div on
这题是豌豆荚二面的一个算法题,和leetcode的某些题目类似。其思路是这样的
public class Solution { String getShortestSubString(String s) { if (s == null || s.length() <= 1) { return s; } // 记录目标字符串的起始索引 int start = 0, end = s.length() - 1; // 记录目标字符串的开始位置 int pStart = 0; Map<Character, List<Integer>> map = new HashMap<Character, List<Integer>>(); for (int i = 0; i < s.length(); i++ ) { map.put(s.charAt(i), null); } int remainingCharacter = map.keySet().size(); for (int i = 0; i < s.length(); i++ ) { char c = s.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(s.charAt(pStart)).size() > 1) { map.get(s.charAt(pStart)).remove(0); pStart++ ; } if (remainingCharacter == 0) { if (i - pStart < end - start) { start = pStart; end = i; } } } return s.substring(start, end +1); } @Test public void test() { System.out.println(getShortestSubString("abcddbccaaabcefggf")); } }
标签:style blog io ar java for sp div on
原文地址:http://blog.csdn.net/jiewuyou/article/details/40682775