串联所有单词的子串(leetcode30)

给定一个字符串 s 和一些长度相同的单词 words。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。

注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。

示例 1:

输入:
s = "barfoothefoobarman",
words = ["foo","bar"]
输出:[0,9]
解释:
从索引 0 和 9 开始的子串分别是 "barfoo" 和 "foobar" 。
输出的顺序不重要, [9,0] 也是有效答案。

解析:

用一个HashMap1 存储需要匹配的words词,再用一个HashMap2存储当前遍历的字符串s中的存在的单词,

如果HashMap2中存在的单词的数量大于HashMap1中的单词数量,说明不匹配;

如果最后HashMap2中匹配到的单词数据恰好等于HashMap1中的单词数量,则符合条件。

public class leetcode30 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String s = "barfoothefoobarman";
        String[] words = new String[]{"foo","bar"};
        
        System.out.println(findSubstring(s,words));
    }

    public static List<Integer> findSubstring(String s, String[] words) {

        List<Integer> res = new ArrayList<Integer>();
        int wordNum = words.length;
        if(wordNum==0){
            return res;
        }
        int wordLen = words[0].length();
        //HashMap1 存所有单词
        HashMap<String,Integer> allWords = new HashMap<String,Integer>();
        for(String w:words){
            Integer value = allWords.get(w);
            allWords.put(w, (value==null?0:value)+1);
        }
        //遍历所有子串
        for(int i=0;i<s.length()-wordNum*wordLen+1;i++){
            //HashMap2 存当前扫描的字符串含有的单词
            HashMap<String,Integer> hasWords = new HashMap<String,Integer>();
            int num =0;
            //判断该子串是否符合
            while(num<wordNum){
                String word = s.substring(i+num*wordLen,i+(num+1)*wordLen);
                //判断该单词在HashMap1 中
                if(allWords.containsKey(word)){
                    Integer value = hasWords.get(word);
                    hasWords.put(word, (value==null?0:value)+1);
                    //判断当前单词的value和HashMap1中的该单词的value
                    if(hasWords.get(word)>allWords.get(word)){
                        break;
                    }
                }else{
                    break;
                }
                num++;
            }
            //判断是不是所有单词都符合条件
            if(num==wordNum){
                res.add(i);
            }
        }
        
        return res;
    }
}
原文地址:https://www.cnblogs.com/Vincent-yuan/p/14567844.html