LeetCode-Substring with Concatenation of All Words

本文提供了一种使用最小滑动窗口的方法来解决LeetCode上的Substring with Concatenation of All Words问题,通过将字符串S按单词长度分组,有效地找出所有起始索引,这些索引指向的是由L中的每个单词恰好一次且无间隔字符组成的子串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作者:disappearedgod
时间:2014-10-4

题目

Substring with Concatenation of All Words

  Total Accepted: 13715  Total Submissions: 76035 My Submissions

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


解法

最小滑动窗口(Java AC的代码是448ms)

因为L中所有单词的长度是一样的,这样根据wordLen,可以将S分为wordLen组,实际意思是这样的。
以题目中barfoothefoobarman举例,L中单词长度为3,可以分为
bar|foo|the|foo|bar|man
ba|rfo|oth|efo|oba|rma|n
b|arf|oot|hef|oob|arm|an
这样,针对每个分组,可以利用最小滑动窗口的思想,快速的判断是否包含需要的字符串。
直观上来看,1和2好像都是需要从每个字符开始搜索,实际上,2利用两个指针去在S中寻找满足条件的字符串,并且是每次+wordLen,而且不会重复的去统计,节省了很多时间。

代码

public class Solution {
    public List<Integer> findSubstring(String S, String[] L) {
        List<Integer> retlist = new ArrayList<Integer>();
        int wordLen = L[0].length();
        int size = L.length;
        int slen = S.length();
        int max = slen - wordLen + 1;
        if(size == 0)
            return retlist;
        int len_match = wordLen * L.length;
        if(len_match > S.length())
            return retlist;
        
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for(int i = 0; i< size; ++i){
            if(map.containsKey(L[i]))
                map.put(L[i],map.get(L[i])+1);
            else
                map.put(L[i], 1);
        }
        
        for(int i = 0; i < wordLen; i++){
            //boolean flag = true;
            HashMap<String, Integer> tmpMap = new HashMap<String, Integer>();
            int count = 0;
            int start = i;
            for(int j = start; j < max; j += wordLen){
                String str = S.substring(j, j + wordLen);
                if(!map.containsKey(str)){
                    tmpMap.clear();
                    count = 0;
                    start = j + wordLen;
                    continue;
                }
                //map has this str
                if(tmpMap.containsKey(str))
                    tmpMap.put(str, tmpMap.get(str)+1);
                else
                    tmpMap.put(str, 1);
                
                if(tmpMap.get(str) <= map.get(str)){
                    count++;
                }else{
                    while(tmpMap.get(str) > map.get(str)){
                        str = S.substring(start, start + wordLen);
                        tmpMap.put(str, tmpMap.get(str) - 1);
                        if(tmpMap.get(str) < map.get(str))
                            count--;
                        start +=wordLen;
                    }
                }
                if(count == size){
                    retlist.add(start);
                    str = S.substring(start, start + wordLen);
                    tmpMap.put(str, tmpMap.get(str)-1);
                    count--;
                    start += wordLen;
                }
                
            }
        }
        return retlist;
        
    }
}


结果

Submit Time Status Run Time Language
15 minutes ago Accepted 480 ms java

返回


相关博客
### 使用Transformer模型进行图像分类的方法 #### 方法概述 为了使Transformer能够应用于图像分类任务,一种有效的方式是将图像分割成固定大小的小块(patches),这些小块被线性映射为向量,并加上位置编码以保留空间信息[^2]。 #### 数据预处理 在准备输入数据的过程中,原始图片会被切分成多个不重叠的patch。假设一张尺寸为\(H \times W\)的RGB图像是要处理的对象,则可以按照设定好的宽度和高度参数来划分该图像。例如,对于分辨率为\(224\times 224\)像素的图像,如果选择每边切成16个部分的话,那么最终会得到\((224/16)^2=196\)个小方格作为单独的特征表示单元。之后,每一个这样的补丁都会通过一个简单的全连接层转换成为维度固定的嵌入向量。 ```python import torch from torchvision import transforms def preprocess_image(image_path, patch_size=16): transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), # 假设目标分辨率是224x224 transforms.ToTensor(), ]) image = Image.open(image_path).convert('RGB') tensor = transform(image) patches = [] for i in range(tensor.shape[-2] // patch_size): # 高度方向上的循环 row_patches = [] for j in range(tensor.shape[-1] // patch_size): # 宽度方向上的循环 patch = tensor[:, :, i*patch_size:(i+1)*patch_size, j*patch_size:(j+1)*patch_size].flatten() row_patches.append(patch) patches.extend(row_patches) return torch.stack(patches) ``` #### 构建Transformer架构 构建Vision Transformer (ViT),通常包括以下几个组成部分: - **Patch Embedding Layer**: 将每个图像块转化为低维向量; - **Positional Encoding Layer**: 添加绝对或相对位置信息给上述获得的向量序列; - **Multiple Layers of Self-Attention and Feed Forward Networks**: 多层自注意机制与前馈神经网络交替堆叠而成的核心模块; 最后,在顶层附加一个全局平均池化层(Global Average Pooling)以及一个多类别Softmax回归器用于预测类标签。 ```python class VisionTransformer(nn.Module): def __init__(self, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, drop_rate=0.): super().__init__() self.patch_embed = PatchEmbed(embed_dim=embed_dim) self.pos_embed = nn.Parameter(torch.zeros(1, self.patch_embed.num_patches + 1, embed_dim)) self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) dpr = [drop_rate for _ in range(depth)] self.blocks = nn.Sequential(*[ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=dpr[i], ) for i in range(depth)]) self.norm = nn.LayerNorm(embed_dim) self.head = nn.Linear(embed_dim, num_classes) def forward(self, x): B = x.shape[0] cls_tokens = self.cls_token.expand(B, -1, -1) x = self.patch_embed(x) x = torch.cat((cls_tokens, x), dim=1) x += self.pos_embed x = self.blocks(x) x = self.norm(x) return self.head(x[:, 0]) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值