zoukankan      html  css  js  c++  java
  • 【LeetCode】Substring with Concatenation of All Words

    You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

    For example, given:
    S: "barfoothefoobarman"
    L: ["foo", "bar"]

    You should return the indices: [0,9].
    (order does not matter).

    思路:用一个hashmap保存链表L,对S进行扫描,若每一个子单词在L中出现且仅出现一次,则满足条件。

    public class Solution {
        public ArrayList<Integer> findSubstring(String S, String[] L) {
            ArrayList<Integer> ret = new ArrayList<Integer>();
        	if (S == null || L == null) {
    			return ret;
    		}
        	int length_words = L[0].length();
        	int length_list = L.length;
        	int length_str = length_words*length_list;
        	
        	HashMap<String, Integer> list_words = new HashMap<String, Integer>();
        	for (String word : L) {
    			if (!list_words.containsKey(word)) {
    				list_words.put(word, 1);
    			}
    			else list_words.put(word, list_words.get(word)+1);
    		}
        	
        	for (int i = 0; i <= S.length()-length_str; i++) {
    			String tmp = S.substring(i, i+length_str);
    			
    			
    			HashMap<String, Integer> tmp_hashHashMap = (HashMap<String, Integer>)list_words.clone();
    			int j;
    			for (j = 0; j < length_list; j++) {
    				String tmpword = tmp.substring(j*length_words, j*length_words+length_words);
    				if (!tmp_hashHashMap.containsKey(tmpword)) {
    					break;
    				}
    				else if (tmp_hashHashMap.get(tmpword) <= 0) {
    					break;
    				}
    				else tmp_hashHashMap.put(tmpword, tmp_hashHashMap.get(tmpword)-1);
    			}
    			
    			if (j == length_list) {
    				ret.add(i);
    			}
    		}
        	return ret;
        }
    }


  • 相关阅读:
    java入门 (七) 面向对象(三)
    java入门 (七) 面向对象(二)
    java入门 (七) 面向对象(一)
    ajax异步请求,$.each遍历拼接数据
    java入门 (六) 数组(二)
    java入门 (六) 数组(一)
    java入门 (五) 方法
    微信小程序
    776C Molly's Chemicals --- 前缀和
    CF 458C Elections --- 三分|线段树
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4236446.html
Copyright © 2011-2022 走看看