Loading

力扣(LeetCode) - 统计重复个数

一. 题目

定义 str = [s, n] 表示 str 由 n 个字符串 s 连接构成。

例如,str == ["abc", 3] == "abcabcabc" 。

如果可以从 s2 中删除某些字符使其变为 s1,则称字符串 s1 可以从字符串 s2 获得。

例如,根据定义,s1 = "abc" 可以从 s2 = "abdbec" 获得,仅需要删除加粗且用斜体标识的字符。

现在给你两个字符串 s1 和 s2 和两个整数 n1 和 n2 。由此构造得到两个字符串,其中 str1 = [s1, n1]、str2 = [s2, n2] 。

请你找出一个最大整数 m ,以满足 str = [str2, m] 可以从 str1 获得。

示例 1:

输入:s1 = "acb", n1 = 4, s2 = "ab", n2 = 2

输出:2

示例 2:

输入:s1 = "acb", n1 = 1, s2 = "acb", n2 = 1

输出:1

提示:

1 <= s1.length, s2.length <= 100

s1 和 s2 由小写英文字母组成

1 <= n1, n2 <= 106

二. 答案

class Solution {
    public int getMaxRepetitions(String s1, int n1, String s2, int n2) {
        // 创建两个字符串缓冲区存储拼接后的字符串
        StringBuilder splice1 = new StringBuilder();
        StringBuilder splice2 = new StringBuilder();
        // acb acb acb acb
        for (int i = 0; i < n1; i++) {
            splice1.append(s1);
        }
        // ab ab
        for (int i = 0; i < n2; i++) {
            splice2.append(s2);
        }
        // 统计重复个数
        int count = 0;
        // 拆分为字符串数组
        char[] charArray = splice2.toString().toCharArray();
        for (int i = 1; i <= charArray.length; i++) {
            // 获取到拆分后的每一个字符
            String tempStr = String.valueOf(charArray[i - 1]);
            // 获取到该字符在字符串1中的索引位置
            int indexOf = splice1.indexOf(tempStr, 0);
            // 退出条件
            if (indexOf == -1) {
                break;
            }
            // 在字符串1中删除该字符
            splice1.delete(0, indexOf + 1);
            // 拆分后的所有字符都匹配上了
            if (i == charArray.length) {
                count++;
                i = 0;
            }
        }
        return count;
    }
}
posted @ 2022-10-28 20:33  Schieber  阅读(51)  评论(0编辑  收藏  举报