算法:串联所有单词的子串
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                算法:串联所有单词的子串
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                ?給定一個字符串?s?和一些長度相同的單詞?words,找出?s?中恰好可以由?words?中所有單詞串聯形成的子串的起始位置。
注意子串要與?words?中的單詞完全匹配,中間不能有其他字符,但不需要考慮?words?中單詞串聯的順序。
例如:
- 輸入:
s = "barfoothefoobarman", words = ["foo","bar"]
- 輸出:
[0,9]
- 解釋:
從索引 0 和 9 開始的子串分別是 "barfoor" 和 "foobar" ,輸出的順序不重要, [9,0] 也是有效答案!
//串聯所有單詞的子串//兩個hashmap解決問題 public 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();//allWors存放所有單詞,key存放單詞,value存放單詞出現的個數HashMap<String, Integer> allWords = new HashMap<String, Integer>();for (String w : words) {int value = allWords.getOrDefault(w, 0);allWords.put(w, value + 1);}//遍歷所有字符for (int i = 0; i < s.length() - wordNum * wordLen + 1; i++) {//存在掃描字符串中含有的單詞 HashMap<String, Integer> hasWords = new HashMap<String, Integer>();int num = 0;while (num < wordNum) {//取的字符串長度是wordLenString word = s.substring(i + num * wordLen, i + (num + 1) * wordLen);if (allWords.containsKey(word)) {//如果單詞存在,存放在hasWors中int value = hasWords.getOrDefault(word, 0);hasWords.put(word, value + 1);if (hasWords.get(word) > allWords.get(word)) {//大于則不是我們要找的break;}} else {break;}num++;}if (num == wordNum) {res.add(i);}}return res; }鏈接:https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by-w-6/
 ?
總結
以上是生活随笔為你收集整理的算法:串联所有单词的子串的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 算法:环形链表
- 下一篇: golang中小数除以大数为0的坑
