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

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

    For example, given:
    s: "barfoothefoobarman"
    words: ["foo", "bar"]

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

    下面这段代码只能通过三分之二的测试用例,因为a concatenation of each word in wordsexactly once,我能说题目意思给的不明确么?

    网上还有应用“滑动窗口”的时间复杂度为O(n)算法,后面再分析!

     1 class Solution {
     2 public:
     3     vector<int> findSubstring(string s, vector<string>& words) {
     4         vector<int> res;
     5         int wordNum=words.size(),wordLen=words[0].size();
     6         if(s.size()<wordLen*wordNum)
     7             return res;
     8         map<string,int> dic,curWord;
     9         for(int i=0;i<wordNum;i++)
    10         {
    11             dic[words[i]]++;
    12         }
    13         for(int i=0;i<s.size()-wordLen*wordNum;i++)
    14         {
    15             curWord.clear();
    16             int count=0;
    17             for(int j=0;j<wordNum;j++)
    18             {
    19                 string word=s.substr(i+j*wordLen,wordLen);
    20                 if(dic.find(word)==dic.end())
    21                     break;
    22                 curWord[word]++;
    23                 count++;
    24                 if(curWord[word]>dic[word])
    25                     break;
    26             }
    27             if(count==wordNum)
    28                 res.push_back(i);
    29         }
    30         return res;
    31     }
    32 };
    手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
  • 相关阅读:
    SQL语句常见优化方法
    MySql索引
    Zookeeper学习记录(一):设计与实现
    linux下修改防火墙端口对外开放方法
    Kafka的Producer以及Consumer远程调用问题
    kafka与Spring的集成
    Kafka在Linux环境下搭建过程
    kafka-分布式消息系统
    打字母的游戏&Java入门
    SVN流程图协作图
  • 原文地址:https://www.cnblogs.com/chess/p/5073065.html
Copyright © 2011-2022 走看看