Guest User

Untitled

a guest
Jan 18th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. class Solution {
  2. public:
  3. vector<int> findSubstring(string s, vector<string>& words) {
  4. unordered_map<string, int> table;
  5. vector<int> ans;
  6.  
  7. if(words.size() == 0) return ans;
  8.  
  9. int window_size = 0;
  10. int word_size = words[0].length();
  11.  
  12. // building frequency table
  13. for(string word : words){
  14. window_size += word.length();
  15. table[word]++;
  16. }
  17.  
  18. unordered_map<string, int> reference(table);
  19.  
  20. int begin = 0, end = 0, counter = table.size();
  21. vector<string> tokens;
  22.  
  23. if(s.length() < window_size) return ans;
  24.  
  25. // we increment begin and end only in word_size
  26. // there are only word_size possible start points for our window.
  27. // end is actually the start of the last word in window or put in other words
  28. // the real end of window is actually at end + word_size
  29. for(int i = 0; i < word_size; i++){
  30. begin = i; end = i;
  31. table = reference; // reset to original frequency table after every iteration
  32. counter = table.size();
  33.  
  34. while(end + word_size -1 < s.length()){
  35. string lastword = s.substr(end, word_size);
  36.  
  37. if(table.count(lastword) == 1){
  38. table[lastword]--;
  39. if(table[lastword] == 0) counter--;
  40. }
  41.  
  42. if(end + word_size - begin == window_size){
  43. // counter == 0, valid answer !
  44. if(counter == 0){
  45. ans.push_back(begin);
  46. }
  47.  
  48. string firstword = s.substr(begin, word_size);
  49.  
  50. if(table.count(firstword) == 1){
  51. table[firstword]++;
  52. if(table[firstword] > 0) counter++;
  53. }
  54.  
  55. begin += word_size;
  56. }
  57.  
  58. end += word_size;
  59. }
  60. }
  61.  
  62. return ans;
  63. }
  64. };
Add Comment
Please, Sign In to add comment