Repeated String Match

Given two strings A and B, find the minimum number of times A has to be repeated such that B is a substring of it. If no such solution, return -1.

For example, with A = "abcd" and B = "cdabcdab".

Return 3, because by repeating A three times (“abcdabcdabcd”), B is a substring of it; and B is not a substring of A repeated two times ("abcdabcd").

Note:
The length of A and B will be between 1 and 10000.

如果A*N.contains(B),那么求出最小的N,如果没有返回-1

    public int repeatedStringMatch(String A, String B) {
        StringBuilder sb = new StringBuilder();
        int result = 0;
        /**
         * 重复拼接A直到长度大于B,这时候才有可能A.contains(B)
         */
        while (sb.length() < B.length()){
            sb.append(A);
            result++;
        }

        /**
         * 如果A.contains(B),返回结果
         */
        if(sb.toString().contains(B)){
            return result;
        }

        /**
         * 再追加一次A可以cover题目中给出的那种类似于B字符串的情况
         */
        if(sb.append(A).toString().contains(B)){
            return ++result;
        }

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

相关阅读更多精彩内容

友情链接更多精彩内容