zoukankan      html  css  js  c++  java
  • [leetcode] Substring with Concatenation of All Words

    题目:(HashTable,Two Point)

    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).

    题解:

    看代码思路还是很清晰的就是顺着给的string s,找。不过不是找一个字母,而是找一个单词,然后L里面的所有单词又刚好都要来一遍。

    public class Solution {
        public ArrayList<Integer> findSubstring(String S, String[] L) {
            HashMap<String, Integer> Lmap = new HashMap<String, Integer>();
            HashMap<String, Integer> Smap = new HashMap<String, Integer>();
            ArrayList<Integer> result = new ArrayList<Integer>();
            int total = L.length;
            if(total==0)
            return result;
            
            for(int i=0;i<total;i++)
            {
                if(!Lmap.containsKey(L[i]))
                     Lmap.put(L[i], 1);
                else
                {
                    int k = Lmap.get(L[i]);
                    Lmap.put(L[i], k+1);
                }
            }
            
            int len = L[0].length();
            for(int i=0;i<=S.length()-len*total;i++)
            {
                Smap.clear();
                int j = 0;
                for(;j<total;j++)
                {
                    String s = S.substring(i+j*len, i+(j+1)*len);
                    if(!Lmap.containsKey(s))
                        break;
                        
                    if(!Smap.containsKey(s))
                        Smap.put(s, 1);
                    else
                    {
                        int k = Smap.get(s);
                        Smap.put(s, k+1);
                    }
                    if(Smap.get(s)>Lmap.get(s))
                        break;
                }
                if(j==total)
                {
                    result.add(i);
                }
            }
            return result;
        }
    }
  • 相关阅读:
    javascript事件列表解说
    如何在ASP.NET页面中嵌入WINFORM控件
    ASP.NET 刷新后如何保持网页的位置
    JS的event 对象
    imp导入数据到ORACLE遭遇ORA12899错误
    求鞍点
    全排列递归实现
    三点顺序
    NYoj 14会场安排问题
    strchr和strstr函数
  • 原文地址:https://www.cnblogs.com/fengmangZoo/p/4194923.html
Copyright © 2011-2022 走看看