[leetcod]Substring with Concatenation of All Words

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S:"barfoothefoobarman"
L:["foo", "bar"]

You should return the indices:[0,9].
(order does not matter).

https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/

思路1:暴力法,假设L中的单位长度为n,依次从S中取长度为n的子串,如果在L中,就记下来。需要借助hash或map,如果整个L都匹配完了,就算是一个concatenation;当匹配错误的时候,S右移一个位置。

思路2(详见参考2):优化,双指针法,思想类似 Longest Substring Without Repeating Characters, 复杂度可以达到线性。

 

思路1:

public class Solution {
	public ArrayList<Integer> findSubstring(String S, String[] L) {
		if (S == null || L == null)
			return null;
		int size = L.length;
		int len = L[0].length();
		ArrayList<Integer> res = new ArrayList<Integer>();

		HashMap<String, Integer> expected = new HashMap<String, Integer>();
		for (String each : L) {
			Integer old = expected.get(each);
			if (old == null)
				expected.put(each, 1);
			else
				expected.put(each, old + 1);
		}
		HashMap<String, Integer> real = new HashMap<String, Integer>();
		int i;

		for (i = 0; i <= S.length() - size * len; i++) {
			real.clear();

			int j, k = 0;
			for (j = i; j < i + size * len; j = j + len, k++) {
				String sub = S.substring(j, j + len);
				if (expected.containsKey(sub)) {
					Integer old = real.get(sub);
					if (old == null)
						real.put(sub, 1);
					else
						real.put(sub, old + 1);

					if (real.get(sub) > expected.get(sub))
						break;

				} else
					break;

			}
			if (k == size)
				res.add(i);

		}

		return res;
	}

	public static void main(String[] args) {
		// String S = "barfoothefoobarman";
		// String[] L = { "foo", "foo" };
		// System.out.println(new Solution().findSubstring(S, L));

		String S = "a";
		String[] L = { "a" };
		System.out.println(new Solution().findSubstring(S, L));
	}
}

思路2(待实现中):

 

第二遍记录:(有bug,第四遍已修复)

补充思路2的实现:

  注意几个长度的区分,S.length, L.length, L[0].length。

  注意双指针,什么时候移动左指针。

public class Solution {
    public ArrayList<Integer> findSubstring(String S, String[] L) {
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (S == null || L == null || L.length == 0 || S.length() == 0)
            return res;
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for (String each : L) {
            if (map.containsKey(each)) {
                map.put(each, map.get(each) + 1);
            } else {
                map.put(each, 1);
            }
        }

        int lenL = L[0].length();
        int lenS = S.length();
        HashMap<String, Integer> curMap = new HashMap<String, Integer>();

        for (int i = 0; i < lenL; i++) {
            curMap.clear();
            int count = 0;
            int left = i;
            for (int j = i; j <= lenS - lenL; j = j + lenL) {
                String str = S.substring(j, j + lenL);
                if (map.containsKey(str)) {
                    if (curMap.containsKey(str)) {
                        curMap.put(str, curMap.get(str) + 1);
                    } else {
                        curMap.put(str, 1);
                    }

                    if (curMap.get(str) <= map.get(str)) {
                        count++;
                    } else {
                        while (curMap.get(str) > map.get(str)) {
                            String tmp = S.substring(left, left + lenL);
                            curMap.put(tmp, curMap.get(tmp) - 1);
                            left += lenL;
                        }

                    }

                    if (count == L.length) {
                        res.add(left);
                        String tmp = S.substring(left, left + lenL);
                        curMap.put(tmp, curMap.get(tmp) - 1);
                        count--;
                        left += lenL;
                    }

                } else {
                    curMap.clear();
                    count = 0;
                    left = j + lenL;
                }

            }

        }
        return res;

    }

}

 

第三遍记录:方法2

  注意curMap每次循环清空

  注意j的终止范围。

  注意左边窗口的移动。

 

第四遍:

发现一个bug,关于count的更新问题,移动左窗口时要记得count--。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Solution {
    public List<Integer> findSubstring(String s, String[] l) {
        List<Integer> res = new ArrayList<Integer>();
        if (s == null || l == null || l.length == 0)
            return res;
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (int i = 0; i < l.length; i++) {
            if (map.containsKey(l[i]))
                map.put(l[i], map.get(l[i]) + 1);
            else
                map.put(l[i], 1);
        }

        int wordLen = l[0].length();
        Map<String, Integer> curMap = new HashMap<String, Integer>();
        for (int i = 0; i < wordLen; i++) {
            int left = i;
            int count = 0;
            curMap.clear();

            for (int j = i; j <= s.length() - wordLen; j += wordLen) {
                String cur = s.substring(j, j + wordLen);
                if (map.containsKey(cur)) {
                    if (curMap.containsKey(cur)) {
                        curMap.put(cur, curMap.get(cur) + 1);
                    } else {
                        curMap.put(cur, 1);
                    }
            //always add, if add more, we will remove later count
++; while (curMap.get(cur) > map.get(cur)) { String toRemove = s.substring(left, left + wordLen); curMap.put(toRemove, curMap.get(toRemove) - 1); left += wordLen;
               //don't forget this count
--; } if (count == l.length) { res.add(left); String toRemove = s.substring(left, left + wordLen); curMap.put(toRemove, curMap.get(toRemove) - 1); left += wordLen; count--; } } else { count = 0; curMap.clear(); left = j + wordLen; } } } return res; } public static void main(String[] args) { String s = "ababaaba"; String[] l = { "a", "b" }; System.out.println(new Solution().findSubstring(s, l)); } }

 

 

 

参考:

http://blog.csdn.net/ojshilu/article/details/22212703

http://blog.csdn.net/linhuanmars/article/details/20342851

 

 

 

 

 

posted @ 2014-06-26 19:40  jdflyfly  阅读(212)  评论(0编辑  收藏  举报