030 Substring with Concatenation of All Words 与所有单词相关联的字串
生活随笔
收集整理的這篇文章主要介紹了
030 Substring with Concatenation of All Words 与所有单词相关联的字串
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)字符串 s 和一些長度相同的單詞 words,找出 s 與 words 中所有單詞(words 每個(gè)單詞只出現(xiàn)一次)串聯(lián)一起(words中組成串聯(lián)串的單詞的順序隨意)的字符串匹配的所有起始索引,子串要與串聯(lián)串完全匹配,中間不能有其他字符。
舉個(gè)例子,給定:
s:"barfoothefoobarman"
words:["foo", "bar"]
你應(yīng)該返回的索引: [0,9]。(任意順序)
詳見:https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/
Java實(shí)現(xiàn):
class Solution {public List<Integer> findSubstring(String s, String[] words) {List<Integer> res=new ArrayList<Integer>();if(s.isEmpty()||s==null||words==null||words.length==0){return res;}int n=words.length;int m=words[0].length();Map<String,Integer> m1=new HashMap<String,Integer>();for(String str:words){if(m1.containsKey(str)){m1.put(str,m1.get(str)+1);}else{m1.put(str,1);}}for(int i=0;i<=s.length()-n*m;++i){Map<String,Integer> m2=new HashMap<String,Integer>();int j=0;for(;j<n;++j){String t=s.substring(i+j*m,i+j*m+m);if(!m1.containsKey(t)){break;}if(m2.containsKey(t)){m2.put(t,m2.get(t)+1);}else{m2.put(t,1);}if(m2.get(t)>m1.get(t)){break;}}if(j==n){res.add(i);}}return res;} }參考:https://www.cnblogs.com/grandyang/p/4521224.html
https://blog.csdn.net/fly_yr/article/details/47957459
轉(zhuǎn)載于:https://www.cnblogs.com/xidian2014/p/8687693.html
總結(jié)
以上是生活随笔為你收集整理的030 Substring with Concatenation of All Words 与所有单词相关联的字串的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 最易懂的layui分页
- 下一篇: Python中MRO