zoukankan      html  css  js  c++  java
  • LeetCode--Substring with Concatenation of All Words

    通过hash记录L中各个单词出现的次数,由于每个单词仅仅在S的解中出现一次,且单词长度一样,所以还是很好处理的。

    但是有一个问题需要注意:

    string的length函数返回的size_t是无符号的。参看代码注释1

    http://www.cplusplus.com/reference/string/string/length/

     1 class Solution {
     2 public:
     3     vector<int> findSubstring(string S, vector<string> &L) {
     4         int lSize = L.size();
     5         vector<int> res;
     6         if(lSize == 0)
     7         {
     8             return res;
     9         }
    10 
    11         map<string,int> countL;
    12         int i;
    13         for(i = 0 ; i < lSize ; ++i)
    14         {
    15             if(countL.find(L[i]) != countL.end())
    16                 countL[L[i]]++;
    17             else
    18                 countL[L[i]] = 1;
    19         }
    20         map<string,int> countS;
    21         int wordSize = L[0].length();
    22         //cout<<S.length()<<lSize<<wordSize<<endl;
    23         int len = S.length();
    24         //cout<<len-(lSize*wordSize)<<endl;
    25         for(i = 0 ; i <= len-lSize*wordSize;++i)
    //注释1:这里一开始我是直接写的S.length()替代len的,但是当S.length()小于lsize*wordsize的时候,就会出现返回的无符号整型很大很大
    26 { 27 int j; 28 countS.clear(); 29 for(j = 0 ; j < lSize ; ++j) 30 { 31 string word = S.substr(i+j*wordSize,wordSize); 32 if(countS.find(word) != countS.end()) 33 { 34 ++countS[word]; 35 if(countS[word] > countL[word]) 36 break; 37 } 38 else if(countL.find(word) != countL.end()) 39 { 40 countS[word] = 1; 41 } 42 else 43 break; 44 } 45 if(j == lSize) 46 { 47 res.push_back(i); 48 } 49 } 50 return res; 51 } 52 };



  • 相关阅读:
    第一次结对作业
    第一次博客作业
    个人总结
    第三次个人作业
    第二次结对作业
    第一次结对作业
    第一次个人编程作业
    第一次博客作业
    第三次个人作业——用例图设计
    第二次结对作业
  • 原文地址:https://www.cnblogs.com/cane/p/3898340.html
Copyright © 2011-2022 走看看