zoukankan      html  css  js  c++  java
  • leetcode: Substring with Concatenation of All Words

    http://oj.leetcode.com/problems/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).

    思路

    L里每个单词长度一样,写循环就方便了很多。先初始化一个map,统计L里每个单词出现的次数。每次循环如果某个单词没出现或者超出L中出现的错误就中断。

     1 class Solution {
     2 public:
     3     vector<int> findSubstring(string S, vector<string> &L) {
     4         int l_size = L.size();
     5         
     6         if (l_size <= 0) {
     7             return vector<int>();
     8         }
     9         
    10         vector<int> result;
    11         map<string, int> word_count;
    12         int word_size = L[0].size();
    13         int i, j;
    14         
    15         for (i = 0; i < l_size; ++i) {
    16             ++word_count[L[i]];
    17         }
    18         
    19         map<string, int> counting;
    20         
    21         for (i = 0; i <= (int)S.length() - (l_size * word_size); ++i) {
    22             counting.clear();
    23             
    24             for (j = 0; j < l_size; ++j) {
    25                 string word = S.substr(i + j * word_size, word_size);
    26                 
    27                 if (word_count.find(word) != word_count.end()) {
    28                     ++counting[word];
    29                     
    30                     if (counting[word] > word_count[word]) {
    31                         break;
    32                     }
    33                 }
    34                 else {
    35                     break;
    36                 }
    37             }
    38             
    39             if (j == l_size) {
    40                 result.push_back(i);
    41             }
    42         }
    43         
    44         return result;
    45     }
    46 };
  • 相关阅读:
    not syncing: Attempted to kill init
    PhpStudy如何开启Apache的gzip压缩功能?
    去掉桌面图标快捷箭头
    PS中10种样式操作
    Mysql数据库报错1264
    宝塔建站
    VB错误说明
    Flash的swf文件破解
    PS快捷键
    Mysql双向同步热备份设置
  • 原文地址:https://www.cnblogs.com/panda_lin/p/substring_with_concatenation_of_all_words.html
Copyright © 2011-2022 走看看