Created
February 21, 2013 14:05
-
-
Save pdu/5004927 to your computer and use it in GitHub Desktop.
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 matte…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #define MAXN 10000 | |
| int f[MAXN]; | |
| int flag[MAXN]; | |
| int num[MAXN]; | |
| class Solution { | |
| public: | |
| vector<int> findSubstring(string S, vector<string> &L) { | |
| memset(f, -1, sizeof(f)); | |
| int m = S.length(); | |
| int n = L.size(); | |
| int len = L[0].length(); | |
| for (int i = 0; i < m; ++i) { | |
| for (int j = 0; j < n; ++j) { | |
| bool match = true; | |
| for (int k = 0; k < len; ++k) | |
| if (L[j][k] != S[i + k]) { | |
| match = false; | |
| break; | |
| } | |
| if (match) { | |
| f[i] = j; | |
| break; | |
| } | |
| } | |
| } | |
| memset(num, 0, sizeof(num)); | |
| for (int i = 0; i < n; ++i) { | |
| if (num[i] != 0) | |
| continue; | |
| num[i]++; | |
| for (int j = i + 1; j < n; ++j) | |
| if (L[i] == L[j]) { | |
| num[j]--; | |
| num[i]++; | |
| } | |
| } | |
| vector<int> ans; | |
| for (int i = 0; i <= m - n * len; ++i) { | |
| memset(flag, 0, sizeof(flag)); | |
| int cnt = 0; | |
| for (int j = 0; j < n; ++j) { | |
| int k = f[i + j * len]; | |
| if (k != -1 && flag[k] < num[k]) { | |
| flag[k]++; | |
| cnt++; | |
| } | |
| else | |
| break; | |
| } | |
| if (cnt == n) | |
| ans.push_back(i); | |
| } | |
| return ans; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment