• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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.

The idea is to keep string builder and appending until the length A is greater or equal to B.

use a while loop to keep adding A to stringBuilder until sb.length() >= B.length(); see if B is a substring of sb.

why == should break as well?  because it's possible for sb == B. like A = "ABC", B = "ABCABC"

 1 class Solution {
 2     public int repeatedStringMatch(String A, String B) {
 3         StringBuilder sb = new StringBuilder();
 4         int res = 0;
 5         while (sb.length() < B.length()) {
 6             sb.append(A);
 7             res ++;
 8         }
 9         if (sb.toString().contains(B)) return res;
10         if (sb.append(A).toString().contains(B)) return ++res;
11         return -1;
12     }
13 }

 

posted @ 2019-10-15 15:28  neverlandly  阅读(73)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3