leetcode 30. Substring with Concatenation of All Words

    xiaoxiao2021-03-25  111

    状态不好,记录一下 LTE,赶快调整状态!

    public class Solution { public static void main(String[] args){ String s = "barfoofoobarthefoobarman"; Solution k = new Solution(); String[] words = {"foo","bar","the"}; List<Integer> ans = k.findSubstring(s,words); for(int a :ans){ System.out.println(a); } } public List<Integer> findSubstring(String s, String[] words) { int n = words.length; int k = words[0].length(); List<Integer> res = new ArrayList<Integer>(); Map<String,Integer> wordset = new HashMap<String,Integer>(); for(String word:words){ if(wordset.containsKey(word)){ int t = wordset.get(word); wordset.put(word, t+1); }else{ wordset.put(word, 1); } } Map<String,Integer> copy = new HashMap<String,Integer>(wordset); int l = s.length(); int cnt = 0; int start = 0; while(start+k*n<=l){ int j = start; while(j+k<=l){ String cur = s.substring(j,j+k); if(wordset.containsKey(cur)){ int t = wordset.get(cur); if(t!=0){ //find a word then check if statisfy wordset.put(cur,--t); cnt++; //if(cnt==1) start = j; // record start pos if(cnt==n){ //check if statisfy res.add(j+k-n*k); break;//j++; //next turn }else{ j = j+k; //next word } }else{ //not found then j++; break; } }else{ //not found then j++; break; } } wordset = new HashMap<String,Integer>(copy); cnt = 0; start++; } return res; } }

    转载请注明原文地址: https://ju.6miu.com/read-10692.html

    最新回复(0)