代码随想录算法训练营第九天 | 字符串部分算法题

28. 实现 strStr()

题目链接 给你两个字符串 haystackneedle ,请你在 haystack 字符串中找出 needle 字符串的第一个匹配项的下标(下标从 0 开始)。如果 needle 不是 haystack 的一部分,则返回 -1

解法一: 暴力解法

  1. 遍历haystack,遇到和needle首字母相同的字符时,开始从haystack中截取needle长度的字串
  2. 判断字串和目标字符串是否相等,相等返回下标,否则继续遍历
class Solution {
    public int strStr(String haystack, String needle) {
        int start = 0;
        while (start < haystack.length()) {
            // 首字母相等
            if (haystack.charAt(start) == needle.charAt(0)) {
                String s = "";
                // haystack剩余字子串要足够截取
                if (haystack.length() - start >=  needle.length()) {
                    for (int i = start; i < needle.length() + start; i++) {
                        s += haystack.charAt(i);
                    }
                    if (s.equals(needle)) {
                        break;
                    }
                }
            }
            start ++;
        }
        int result = start == haystack.length() ? -1 : start;
        return result;
    }
}

459. 重复的子字符串

题目链接 给定一个非空的字符串 s ,检查是否可以通过由它的一个子串重复多次构成。

解法:枚举法。如果一个长度为 n 的字符串 s 可以由它的一个长度为 n1 的子串 s1 重多次构成。那么一定满足以下条件

  1. n一定是n1的倍数
  2. s1一定是s的前缀,并且在前缀s1之后的每个位置上的字符s[i],一定与s[i - n1]处的字符相等;
class Solution {
    public boolean repeatedSubstringPattern(String s) {
        int n = s.length();
        // 因为子串至少需要重复一次, 字串长度不会大于s的一半; i为子串最后一个位置的下标
        for (int i = 1; i <= n / 2; ++i) {
            if (n % i == 0) {
                boolean result = true;
                for (int j = i; j < n; ++j) {
                    if (s.charAt(j) != s.charAt(j - i)) {
                        result = false;
                        break;
                    }
                }
                if (result) {
                    return true;
                }
            } 
        }
        return false;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值