686. Repeated String Match

来源:互联网 发布:java程序设计pdf下载 编辑:程序博客网 时间:2024/05/17 01:17

686. 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”).

  • 题目大意:给定两个字符串A,B,判断A重复多少次,B会变为其的子串,如果无解,返回-1。

  • 思路:使用StringBulider

  • 代码

    class Solution {  public int repeatedStringMatch(String A, String B) {           int count = 0;      StringBuilder stringBuilder = new StringBuilder();      while (stringBuilder.length() < B.length()) {          stringBuilder.append(A);          count++;      }      if (stringBuilder.toString().contains(B)) {          return count;      }      if(stringBuilder.append(A).toString().contains(B)) return ++count;      return -1;  }}
原创粉丝点击