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

    自己想的大体思路还是对的,不过可以改进的很多,最后网上找了个勉勉强强过large的答案,用map实在太容易超时了。。

     1 class Solution {
     2 public:
     3     vector<int> findSubstring(string S, vector<string> &L) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int len = L[0].size();
     7         int size = L.size();
     8         map<string, int> T;
     9         map<string, int> V;
    10         for (int i = 0; i < L.size(); i++) T[L[i]]++;
    11         vector<int> ret;
    12         for (int i = 0; i < S.size()-size*len+1; i++) {
    13             V.clear();
    14             int j = 0;
    15             for (; j < size; j++) {
    16                 string tmp = S.substr(i+j*len, len);
    17                 if (T.find(tmp) != T.end()) V[tmp]++;
    18                 else break;
    19                 if (V[tmp] > T[tmp]) break;
    20             }
    21             if (j == size) ret.push_back(i);
    22         }
    23         return ret;
    24     }
    25 };

     C#

     1 public class Solution {
     2     public List<int> FindSubstring(string s, string[] words) {
     3         int len = words[0].Length;
     4         int size = words.Length;
     5         Dictionary<string, int> T = new Dictionary<string, int>();
     6         Dictionary<string, int> V = new Dictionary<string, int>();
     7         for (int i = 0; i < size; i++) {
     8             if (T.ContainsKey(words[i])) T[words[i]]++;
     9             else T.Add(words[i], 1);
    10         }
    11         List<int> ans = new List<int>();
    12         for (int i = 0; i < s.Length-size*len+1; i++) {
    13             V.Clear();
    14             int j = 0;
    15             for (; j < size; j++) {
    16                 string tmp = s.Substring(i+j*len, len);
    17                 if (T.ContainsKey(tmp)) {
    18                     if (V.ContainsKey(tmp)) V[tmp]++;
    19                     else V.Add(tmp, 1);
    20                 }
    21                 else break;
    22                 if (V[tmp] > T[tmp]) break;
    23             }
    24             if (j == size) ans.Add(i);
    25         }
    26         return ans;
    27     }
    28 }
    View Code
  • 相关阅读:
    MySQL 8.0系列——轻松改配置,云上友好
    测试expire_logs_days参数
    mongodb单实例安装
    搭建PXC集群指引
    控制mysqldump导出的SQL文件的事务大小
    实战MySQL8.0.17 Clone Plugin
    windows环境下 curl 安装和使用
    git 创建tag , 查看tag , 删除tag
    git 基本操作
    git 一个分支完全覆盖另一个分支
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3033921.html
Copyright © 2011-2022 走看看