Leetcode: Repeated String Match
LeetCode string match
2023-09-11 14:14:07 时间
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 }
相关文章
- Leetcode: Find And Replace in String
- Leetcode: Unique Substrings in Wraparound String
- Leetcode: Number of Segments in a String
- Leetcode: Fizz Buzz
- Leetcode: Shuffle an Array
- Leetcode: Interleaving String
- [leetcode]String to Integer (atoi)
- [LeetCode] Reverse Words in a String
- [LeetCode] Scramble String
- [LeetCode]剑指 Offer 63. 股票的最大利润
- LeetCode 15. 三数之和
- LeetCode二叉树练习(二)
- 【LeetCode】24. Swap Nodes in Pairs (3 solutions)
- 【LeetCode】131. Palindrome Partitioning
- LeetCode OJ 之 Valid Anagram
- Insertion Sort List -- leetcode
- leetcode 8 String to Integer (atoi)
- LeetCode——Combination Sum II
- 【Leetcode】104 :二叉树的最大深度
- [LeetCode] 1239. Maximum Length of a Concatenated String with Unique Characters 串联字符串的最大长度
- [LeetCode] 1104. Path In Zigzag Labelled Binary Tree 之字形二叉树路径
- [LeetCode] 839. Similar String Groups 相似字符串组
- [LeetCode] 887. Super Egg Drop 超级鸡蛋掉落
- [LeetCode] 880. Decoded String at Index 在位置坐标处解码字符串
- [LeetCode] 589. N-ary Tree Postorder Traversal N叉树的后序遍历
- [LeetCode] Beautiful Arrangement II 优美排列之二
- [LeetCode] Add Bold Tag in String 字符串中增添加粗标签
- [LeetCode] Magical String 神奇字符串
- [LeetCode] Unique Substrings in Wraparound String 封装字符串中的独特子字符串
- [LeetCode] 465. Optimal Account Balancing 最优账户平衡
- [LeetCode] 375. Guess Number Higher or Lower II 猜数字大小之二
- [LeetCode] 394. Decode String 解码字符串
- [LeetCode] 148. Sort List 链表排序