[LeetCode] Count The Repetitions

来源:互联网 发布:2017乒超联赛网络直播 编辑:程序博客网 时间:2024/06/03 13:20

Define S = [s,n] as the string S which consists of n connected strings s. For example, ["abc", 3] ="abcabcabc".

On the other hand, we define that string s1 can be obtained from string s2 if we can remove some characters from s2 such that it becomes s1. For example, “abc” can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”.

You are given two non-empty strings s1 and s2 (each at most 100 characters long) and two integers 0 ≤ n1 ≤ 106 and 1 ≤ n2 ≤ 106. Now consider the strings S1 and S2, where S1=[s1,n1] and S2=[s2,n2]. Find the maximum integer M such that [S2,M] can be obtained from S1.

Example:

Input:s1="acb", n1=4s2="ab", n2=2Return:2

代码一:

public class Solution2 {//这个代码只beat 2%  所以不稳定     public int getMaxRepetitions(String s1, int n1, String s2, int n2) {     int re=0; int count1=0,count2=0; int i=0,j=0; char[] arr1=s1.toCharArray(); char[] arr2=s2.toCharArray(); while(count1<n1){ if(arr1[i]==arr2[j]){ j++; if(j==arr2.length){ count2++;j=0; if(count2==n2){ re++; count2=0; } } } i++; if(i==s1.length()){ i=0;count1++; } } return re; }}
代码二:

public class Solution {public int getMaxRepetitions(String s1, int n1, String s2, int n2) { if(s1.length()*n1<s2.length()*n2) return 0; int count1=0,count2=0; int i=0,j=0; char[] arr1=s1.toCharArray(); char[] arr2=s2.toCharArray(); while(count1<n1){ if(arr1[i]==arr2[j]){ j++; if(j==arr2.length){ count2++;j=0; } } i++; if(i==s1.length()){ i=0; count1++; } } return count2/n2; } public static void main(String[] args) {Solution s=new Solution();String s1=  "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";System.out.println(s1.length());String s2= "a";System.out.println(s.getMaxRepetitions(s1, 1000000, s2, 1));}}



原创粉丝点击