Substring with Concatenation of All Words @leetcode

https://oj.leetcode.com/problems/substring-with-concatenation-of-all-words/

基本上就是从头到尾扫描,每次移动一格,不断地在hashmap中删除一个匹配到的字符串。
这里有一个问题。题目中没有讲明L中有重复,而实际上是会有重复的。

leetcode这里写得不是太清楚。所以我们用hashmap来记录各个字串出现的次数。

一开始我用的递归,老是会超时,改为for后就ok了,实际上这个程序使用for来写也不费劲。

public class Solution {
    public List
   
   
    
     findSubstring(String S, String[] L) {
        ArrayList
    
    
     
      rst = new ArrayList
     
     
      
      ();
        
        if (S == null || L == null || L.length == 0) {
            return rst;
        }
        
        HashMap
      
      
       
        s1 = new HashMap
       
       
         (); for(String s: L) { if (s1.containsKey(s)) { s1.put(s, s1.get(s) + 1); } else { s1.put(s, 1); } } int len = S.length(); int sLen = L[0].length(); // 用i来控制扫描的起始位置 for (int i = 0; i <= (len - L.length * sLen); i++) { HashMap 
        
          left = new HashMap 
         
           (s1); // 用j来表示在本次扫描到达的匹配位置 for (int j = i; j <= len - sLen; j+=sLen) { String tmp = S.substring(j, j + sLen); if (left.containsKey(tmp)) { if (left.get(tmp) == 1) { left.remove(tmp); } else { left.put(tmp, left.get(tmp) - 1); } // 将匹配位置往前移动 } else { // 移动到下一个位置 break; } if (left.isEmpty()) { rst.add(i); break; } } } return rst; } } 
          
         
       
      
      
     
     
    
    
   
   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值