• [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;
        }
    }
  • 相关阅读:
    记住密码
    winform 更新服务器程序
    asp.net TreeView
    asp.net excel导出红色字体
    asp.net 图表
    图数据存储初见
    在windows下安装hadoop
    R 语言实现牛顿下降法
    蛇形矩阵
    算法竞赛入门经典习题2-6 排列(permutation)
  • 原文地址:https://www.cnblogs.com/fengmangZoo/p/4194923.html
Copyright © 2020-2023  润新知