【LC467】环绕字符串中唯一的子字符串

题目

把字符串 s 看作是 “abcdefghijklmnopqrstuvwxyz” 的无限环绕字符串,所以 s 看起来是这样的:

"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd...." . 

现在给定另一个字符串 p 。返回 s 中唯一的p的非空子串的数量 。

题解

失败案例

暴力遍历所有子串,并利用set保证子串不重复,在遍历set中的子串并判断是否存在于环绕字符串中,结果超时

class Solution {
    public int findSubstringInWraproundString(String p) {
        int res = 0;
        Set<String> set = new HashSet<>();
        for(int i = 0; i < p.length(); ++i) {
            for(int j = i + 1; j <= p.length(); ++j) {
                String str = p.substring(i, j);
                set.add(str);
            }
        }
        Iterator<String> it = set.iterator();
        while(it.hasNext()) {
            if(isExist(it.next())) res++;
        }
        return res;
    }

    //判断环绕字符串中是否存在当前子串
    public boolean isExist(String s) {
        for(int i = 1; i < s.length(); ++i) {
            int cnt = s.charAt(i) - s.charAt(i - 1);
            if(cnt != 1 && cnt != -25) return false; 
        }
        return true;
    }
}

在这里插入图片描述

官方题解

关键:环绕字符串是周期字符串,知道子串末尾字符和子串长度,即可确定以当前字符结尾的子串的个数

知识点:

  1. 如何确定子串字符连续递增:(p.charAt(i) - p.charAt(i - 1) + 26) % 26 == 1
  2. 数组元素和:Arrays.stream(dp).sum()
class Solution {
    public int findSubstringInWraproundString(String p) {
        int[] dp = new int[26];  //记录以某个字符结尾的环绕子串的最大长度
        int k = 0;
        for(int i = 0; i < p.length(); ++i) {
            if(i > 0 && (p.charAt(i) - p.charAt(i - 1) + 26) % 26 == 1) k++;
            else k = 1;
            dp[p.charAt(i) - 'a'] = Math.max(dp[p.charAt(i) - 'a'], k);
        }
        return Arrays.stream(dp).sum();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值