zoukankan      html  css  js  c++  java
  • 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来降低时间复杂度, 整个的算法很简单。

     1 public class Solution {
     2      int elen = 0;
     3     public ArrayList<Integer> findSubstring(String S, String[] L) {
     4         // Note: The Solution object is instantiated only once and is reused by each test case.
     5         ArrayList<Integer> result = new ArrayList<Integer>();
     6         if(S == null || S.length() == 0) return result;
     7         int slen = S.length();
     8         int n = L.length;
     9         elen = L[0].length();
    10         HashMap<String, Integer> hm = new HashMap<String, Integer>();
    11         for(int i = 0; i < n; i ++){
    12             if(hm.containsKey(L[i])) 
    13                 hm.put(L[i], hm.get(L[i]) + 1);
    14             else                     
    15                 hm.put(L[i], 1);
    16         }
    17         for(int i = 0; i <= slen - n * elen; i ++){
    18             if(hm.containsKey(S.substring(i, i + elen)))
    19                 if(checkOther(new HashMap<String, Integer>(hm), S, i))
    20                     result.add(i);
    21         }
    22         return result;
    23     }
    24     public boolean checkOther(HashMap<String, Integer> hm, String s, int pos){
    25         if(hm.size() == 0)  return true;
    26         if(hm.containsKey(s.substring(pos, pos + elen))){
    27             if(hm.get(s.substring(pos, pos + elen)) == 1)  
    28                 hm.remove(s.substring(pos, pos + elen));
    29             else                                           
    30                 hm.put(s.substring(pos, pos + elen), hm.get(s.substring(pos, pos + elen)) - 1);
    31             return checkOther(hm, s, pos + elen);
    32         }
    33         else return false;
    34     }
    35 }
  • 相关阅读:
    商务邮件
    比较好用的办公软件
    django之创建第6-2个项目-过滤器列表
    Linux管道思想
    django之创建站点之基本流程
    django资料
    Django之 创建第一个站点
    python之获取微信服务器的ip地址
    python之获取微信access_token
    python之模块py_compile用法(将py文件转换为pyc文件)
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3403138.html
Copyright © 2011-2022 走看看