每日一练_56(2021.8.6) 串联所有单词的子串

该博客介绍了一种Java算法,用于在字符串中查找包含给定单词数组的所有单词的连续子串。代码简洁易懂,适用于字符串处理和算法学习。测试案例展示了对于输入字符串'barfoothefoobarman',单词数组['foo', 'bar'],找到的子串为[0, 9]。
摘要由CSDN通过智能技术生成

Substring with Concatenation of All Words

大佬的代码:https://blog.csdn.net/Maybeno1314/article/details/100692030 代码很简洁,也很详细,值得学习和借鉴。

个人微改:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
public class substringWithConcatenationOfAllWords {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("please enter your String :");
        String s = sc.nextLine();
        System.out.println("please enter the size of your substring array :");
        int m = sc.nextInt();
        String str[] = new String[m];
        System.out.println("please enter your substring :");
        for(int i=0;i<m;i++) {
            str[i]=sc.next();
        }
        List<Integer> hah = new ArrayList<>();
        hah = findSubstring(s,str);
        System.out.println(hah);
        sc.close();
    }
    
    static List<Integer> findSubstring(String s,String[] words){
        List<Integer> ans = new ArrayList<>();
        
        int sLen = s.length();
        
        int wordNum = words.length;
        
        if(wordNum == 0) {
            return ans;
        }
        
        int wordLen = words[0].length();
        
        int windowLen = wordLen*wordNum;
        
        HashMap<String,Integer> wordCount = new HashMap<String,Integer>();
        
        for(String word:words) {
            int val = wordCount.getOrDefault(word,0);
            wordCount.put(word,val+1);
        }
        
        for(int i=0;i<sLen-windowLen+1;i++) {
            int count=0;
            HashMap<String,Integer> windowWord = new HashMap<>();
            while(count<wordNum) {
                String word = s.substring(i+count*wordLen,i+(count+1)*wordLen);
                if(wordCount.containsKey(word)) {
                    int val = windowWord.getOrDefault(word,0);
                    windowWord.put(word,val+1);
                    if(windowWord.get(word)>wordCount.get(word)) {
                        break;
                    }
                }else {
                    break;
                }
                count++;
            }
            if(count==wordNum) {
                ans.add(i);
            }
        }
        
        return ans;
    }
}
测试结果:

please enter your String :
barfoothefoobarman
please enter the size of your substring array :
2
please enter your substring :
foo
bar
[0, 9]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是壮壮没错了丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值