博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Substring with Concatenation of All Words
阅读量:6957 次
发布时间:2019-06-27

本文共 2022 字,大约阅读时间需要 6 分钟。

每日算法——leetcode系列


Substring with Concatenation of All Words

Difficulty: Hard

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 words exactly 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).

class Solution {public:    vector
findSubstring(string s, vector
& words) { }};

翻译

与所有单词相关联的字串

难度系数:困难

给定一个字符串s和一些长度相同的单词words,找出s的与words中所有单词(words每个单词只出现一次)串联一起(words中组成串联串的单词的顺序随意)的字符串匹配的所有起始索引,子串要与串联串完全匹配,中间不能有其他字符。

思路

这题对我来说就是理解题意。

先把words中每个单词,以words中每个单词为key, 单词出现的次数为value放入map表中
再在s中每次取三个来去map表找,如果找到则找下三个,如果没找到,则s索引回溯到找到的第一个的索引 + 1。

代码

class Solution {public:    vector
findSubstring(string s, vector
&words) { vector
result; if (s.size() <= 0 || words.size() <= 0) { return result; } if (s.size() < words.size() * words[0].size()) { return result; } int m = static_cast
(s.size()); int n = static_cast
(words.size()); int l = static_cast
(words[0].size()); unordered_map
wordMap; for (int i = 0; i < n; ++i) { if (wordMap.find(words[i]) != wordMap.end()) { wordMap[words[i]]++; } else { wordMap[words[i]] = 1; } } unordered_map
bakWordMap = wordMap; int fisrtIdnex = 0; for (int j = 0; j <= m - l;) { string word = s.substr(j, l); if (wordMap.find(word) == wordMap.end()) { j = ++fisrtIdnex; wordMap = bakWordMap; continue; } j += l; wordMap.at(word)--; if (wordMap.at(word) == 0) { wordMap.erase(word); } if (wordMap.empty()) { result.push_back(fisrtIdnex); wordMap = bakWordMap; } } return result; }};

注: 这个本地测试可以, 但提交提示超时, 再考虑下其他的办法。

转载地址:http://wzqil.baihongyu.com/

你可能感兴趣的文章
提交自己的包到bower、npm中
查看>>
详解 JavaScript 的私有变量
查看>>
网站建设在“互联网+”时代的发展趋势
查看>>
脚本语言不行?JavaScript 重写 Office 365 已进入尾声
查看>>
日志框架 - 基于spring-boot - 设计
查看>>
R语言基础操作①
查看>>
安装 PrestaShop 1.6 - 关于快速安装指南
查看>>
ecshop中ajax的调用原理
查看>>
速查笔记(Linux Shell编程<上>)
查看>>
更换手机设备时如何同步迁移便签内容?
查看>>
Linux进程间通信之共享内存
查看>>
模拟返回的后台数据实现统计图
查看>>
《Linux命令行与shell脚本编程大全》第二十六章 一些有意思的脚本
查看>>
设置文字旋转角度
查看>>
Spring_DI_XML_02
查看>>
uCos-III移植到STM32F10x
查看>>
openssl编译使用
查看>>
不学无数——SpringBoot入门V
查看>>
Android Pie 引入 Keystore 新特性,安全防护再升级
查看>>
前端性能优化之 Composite
查看>>