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).
这道题的意思是这样的,word数组中每一个元素的length都是一样的,在字符串s中寻找一个子串,s可以有word数组中所有的元素拼接起来,每一个元素使用仅且一次。
我的做法就是直接遍历暴力求解,首先分割出所有的可能的字符串,然后逐一的和word数组左匹配,我首先使用的是List做得word数组的匹配,然后试了一下HashMap做的匹配。
代码如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* 本体的做法就是不断的切割出所有可能的字符串, 然后针对每一个字符串做分析
*
* 网上还有使用HashMap的做法,map中保存这string和对应的出现的次数,然后分割出
* 所有可能字符串,使用HashMap加速查询,这个也是可以的,在这里就不赘述了。
*
* */
public class Solution
{
public List<Integer> findSubstring(String s, String[] words)
{
//特殊情况
List<Integer> res=new ArrayList<>();
if(s==null || words==null || s.length()< words.length*words[0].length())
return res;
//切割所有可能的字符串,然后去做比较
int totalLen=words.length*words[0].length();
for(int i=0;i<s.length()-totalLen+1;i++)
{
String tmp=s.substring(i, i+totalLen);
if(cmp(tmp,words))
res.add(i);
}
return res;
}
/* ·
* 这里使用的是list,是考虑到可能存在重复元素
* 从效率上最好用hashset
* */
public boolean cmp(String tmp, String[] words)
{
List<String> one=new ArrayList<>();
for(int i=0;i<tmp.length();i+=words[0].length())
one.add(tmp.substring(i,i+words[0].length()));
for(int i=0;i<words.length;i++)
{
if(one.contains(words[i]))
one.remove(words[i]);
else
return false;
}
return true;
}
/* ·
* 这里使用的是list,是考虑到可能存在重复元素
* 从效率上最好用hashset
* */
public boolean cmpByHashMap(String tmp, String[] words)
{
Map<String, Integer> map=new HashMap<String, Integer>();
for(int i=0;i<tmp.length();i+=words[0].length())
{
String key=tmp.substring(i,i+words[0].length());
int count=map.getOrDefault(key, 0)+1;
map.put(key, count);
}
for(int i=0;i<words.length;i++)
{
if(map.containsKey(words[i]))
{
int count=map.get(words[i]);
if(count==1)
map.remove(words[i]);
else
map.put(words[i], count-1);
}else
return false;
}
return true;
}
}
下面的是C++的做法,使用Map直接做遍历查询即可AC,没想到吧!
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
class Solution
{
public:
vector<int> findSubstring(string s, vector<string>& words)
{
vector<int> res;
if (words.size() <= 0)
return res;
int totalLen = words.size() * words[0].length();
for (int i = 0; i < s.length()-totalLen+1; i++)
{
if (cmp(s.substr(i, totalLen), words))
res.push_back(i);
}
return res;
}
bool cmp(string s, vector<string>& words)
{
map<string, int> mp;
for (int i = 0; i < s.length(); i += words[0].length())
{
string key = s.substr(i, words[0].length());
if ( mp.find(key)== mp.end())
mp[key] = 1;
else
mp[key] = mp[key] + 1;
}
for (int i = 0; i < words.size(); i++)
{
string key = words[i];
if (mp.find(key) == mp.end())
return false;
else
{
int count = mp[key];
if (count == 1)
mp.erase(key);
else
mp[key] = count - 1;
}
}
return true;
}
};