LeetCode466. Count The Repetitions

  1. 題目連接
  2. 題意
    • 定義一個特殊的串, 如今給出串S1和S2的參數, 問: S2最多能夠多少個鏈接起來扔是S1的子序列, 求出這個最大值
  3. 解題思路
    • 注意s1與S1的區別, 能夠去看題目描述, 預處理出s1從s2的每個字符開始匹配, s1能夠匹配到s2串尾的數量, 即若是從s2的當前下標開始匹配, 這一個s1最多能夠匹配多少s2, 這個s1匹配完成後匹配到了s2的哪個字符, 下一個s1匹配s2的話應該從哪個下標開始, 由於串長最長100, 這個預處理時間消耗是不多的, 有了這個預處理的結果, 咱們就能夠O(n)的知道S1能夠匹配多少個s2, 進而推算出匹配多少個S2.
  4. AC代碼
    class Solution {
        public int getMaxRepetitions(String s1, int n1, String s2, int n2) {
            int answer = 0;
        
            ArrayList<Integer> numArrayList = new ArrayList<Integer>();
            ArrayList<Integer> idxArrayList = new ArrayList<Integer>();
        
            for(int i = 0; i < s2.length(); ++i) {
        	int num = 0, idx = i;
        	for(int j = 0; j < s1.length(); ++j) {
        		if(s2.charAt(idx) == s1.charAt(j)) {
        			idx++;
        			if(idx == s2.length()) {
        				num++;
        				idx = 0;
        			}
        		}
        	}
        	numArrayList.add(num);
        	idxArrayList.add(idx);
            }
        
            int idx = 0;
        
            for(int i = 0; i < n1; ++i) {
                answer += numArrayList.get(idx);
                idx = idxArrayList.get(idx);
            }
        
            return answer / n2;
        }
    }
相關文章
相關標籤/搜索