新农上路
- 积分
- 96
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-10-16
- 最后登录
- 1970-1-1
|
第一题,
- public class ShortestSubstringContainOneABC {
- public static void main(String[] args) {
- ShortestSubstringContainOneABC s = new ShortestSubstringContainOneABC();
- System.out.println(s.getShortestSubstringContainOneABC("abdddddcbbaeeec"));
- }
- public String getShortestSubstringContainOneABC(String s) {
- if (s == null || s.length() == 0) {
- return "";
- }
- HashMap<Character, Integer> map = new HashMap<>();
- map.put('a', 0);
- map.put('b', 0);
- map.put('c', 0);
- int start = 0;
- int len = Integer.MAX_VALUE;
- int count = 0;
- String res = "";
- for (int i = 0; i < s.length(); i++) {
- char c = s.charAt(i);
- if (!map.containsKey(c)) {
- continue;
- }
- map.put(c, map.get(c) + 1);
- if (map.get(c) == 1) {
- count++;
- }
- while (start < i && count == 3) {
- if (isValid(map) && i - start + 1 < len) {
- res = s.substring(start, i + 1);
- len = i - start + 1;
- }
- char ch = s.charAt(start++);
- if (!map.containsKey(ch)) {
- continue;
- }
- map.put(ch, map.get(ch) - 1);
- if (map.get(ch) == 0) {
- count--;
- }
- }
- }
- return res;
- }
- private boolean isValid(HashMap<Character, Integer> map) {
- for (int value : map.values()) {
- if (value != 1) {
- return false;
- }
- }
- return true;
- }
- }
复制代码 |
|