LeetCode进阶之路(Substring with Concatenation of All Words)

本文介绍了一种用于查找字符串数组在目标字符串中所有匹配子串起始位置的算法。该算法通过预处理字符串数组并利用排序比对的方式提高查找效率。

You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.

For example, given:
s"barfoothefoobarman"
words["foo", "bar"]

You should return the indices: [0,9].

(order does not matter).

题目:给出一个字符串和一个字符串数组(其中每个字符串长度相等),数组中的字符串组成一个长串,找出字符串中和长串相等的子串,并输出其初始位置。

思路:因为字符串数组中每个元素长度都相等,就可以知道我们目标子串的长度。题目就简化成一个确定长度的字符串和一个数组中元素随机组成的串是否相等,那就可以把这个字符串也分割n个元素的数组,两个数组按顺序排列后比较是否相等即可。

public List<Integer> findSubstring(String s, String[] words) {
        int len = words[0].length()*words.length;//数组元素个数*每个长度
        List<Integer> list = new ArrayList<Integer>();
        List<String> list1 = new ArrayList<String>();
        for(int i = 0; i < words.length;i++) {
            list1.add(words[i]);//把数组中的元素都放到list中,后面减小遍历范围有用
        }
        for(int i = 0;i <= s.length() - len;i++){
            String str = s.substring(i, i + len);//把字符串按len长度分割,如果就这样去判断会超时,因此要排除一些子串,缩小范围
            if(list1.contains(str.substring(0, words[0].length()))){//把那些开头就不符合的串给排除。
                if(find(str, words)){
                    list.add(i);
                }
            }
            
        }
        return list;
    }
    
    public boolean find(String str, String[] words) {
        String[] strWords = new String[words.length];
        int len = words[0].length();
        Arrays.sort(words);//数组按序排列
        for(int i = 0; i < str.length()/len;i++){//把字符串分割,组成一个数组(根据words数组元素的长度来分割)
            strWords[i] = str.substring(i*len, i*len+len);
        }
        Arrays.sort(strWords);//两个数组排序后比较
        for(int i = 0; i< words.length;i++){
            if(!words[i].equals(strWords[i])){
                return false;
            }
        }
        return true;
    }

种一棵树最好的时间是十年前,其次是现在!



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值