题目详情
给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
示例 1:
输入:
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 “barfoo” 和 “foobar” 。
输出的顺序不重要, [9,0] 也是有效答案。
示例 2:
输入:
s = “wordgoodgoodgoodbestword”,
words = [“word”,“good”,“best”,“word”]
输出:[]
解题思路
有个隐藏条件就是单词的长度是一样的 抓住这点就比较容易解决。
代码如下
class Solution {
/**
* @param String $s
* @param String[] $words
* @return Integer[]
*/
function findSubstring($s, $words) {
$result = array();
$num = strlen(current($words));
$long = strlen($s);
for($i=0; $i<=($long-$num);$i++)
{
$res = false;
$tmp = substr($s,$i,$num);
$res = $this->judge($i,$num,$s,$words);
if($res) {
$result[] = $i;
}
}
return $result;
}
function judge($i,$long,$s,$words)
{
$is_word = false;
$total = strlen($s);
for($i;$i<=$total;$i=$i+$long){
$tmp_word = substr($s,$i,$long);
$index = array_search($tmp_word, $words);
if($index !== false ) {
unset($words[$index]);
$is_word = true;
}else {
$is_word = false;
}
if(count($words) == 0 || $is_word == false){
break;
}
}
return $is_word;
}
}
存才的问题
在最后一个case会提示时间超时运行速度不是很好 需要优化 暂时先放着 找个时间优化下