28.1递归删除子串,并求删除次数

题目描述:

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的【位置】、次数 (从0开始),并删除needle。返回 次数。

示例:

示例 1:

输入: haystack = "hellollo", needle = "ll"
输出:2 5 2或者2 3 2【5是不删除needle,3是删除needle】

示例 2:

输入: haystack = "aaaaa", needle = "bba"
输出: 0 0 0

解答:

package code028_ImplementstrStr;
import java.util.ArrayList;
import java.util.List;
public class BaoyanNo1 {
    public static int strStr(String haystack, String needle) {
        // 子串长度为0,返回0
        if (needle.length() == 0) {
            return 0;
        }
        // 子串或者母串为空,返回-1
        if (haystack == null || needle == null) {
            return -1;
        }
        // 子串的个数
        int j = needle.length(), count = 0;
        List<Integer> location = new ArrayList<>();
        // 循环母串,到子串长度前停止
        for (int h = 0; h < haystack.length() - needle.length() + 1; h++) {
            // 使用substring判断是否有子串;注意左闭右开,右侧需要+1
            // substring长度为:end-begin
            if (haystack.substring(h, j + h).equals(needle)) {
                // 保研机考第一题:递归删除子串【substring】,删除次数【count】;
                count++;
                haystack = haystack.substring(0, h) + haystack.substring(h + j, haystack.length());
                // 删除位置【递归删除子串:位置为新字符串;不递归:位置为原始字符串】
                location.add(h);
            }
        }
        System.out.println(count);
        // 不递归的话,可以replaceAll
        // haystack = haystack.replaceAll(needle, "");
        // 递归删除子串后的字符串
        System.out.println(haystack);
        for (int i = 0; i < location.size(); i++) {
            System.out.print(location.get(i) + ";");
        }
        return count;
    }

    public static void main(String[] args) {
        strStr("hellollo", "ll");
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 第四章 字符串操作与正则表达式 1.mail()函数 bool mail (string to, string s...
    梁烨端木阅读 836评论 0 0
  • 字符串的处理介绍 字符串的处理方式 在C语言中字符串是作为字节数组处理的。在Java语言中字符串是作为对象处理的。...
    dptms阅读 1,326评论 0 1
  • 别用自己的标准去要求别人,除非你是老板。别因为别人的行为而大动干戈,不是每个人的思维方式都一样。 在团队合作中,真...
    超元气大大阅读 279评论 0 1
  • 其实也没想到自己能拿到二等奖学金,所以申请了国家励志奖学金,好希望自己可以拿到,可以帮妈妈还一点钱
    五月sn阅读 93评论 0 0

友情链接更多精彩内容