給你兩個數字 num 跟 k ,前者是你要處理的數字,後者是 substring 的寬度,
依照 Sliding Window 的原理,在 num 裡取出所有大小為 k 的 substring ,回傳這些值之中可以整除 num 的值的數量。
點我開啟限制與範例
限制:
1 <= num <= 109
1 <= k <= num.length (taking num as a string)
Example 1:
1 2 3 4 5 6
Input: num = 240, k = 2 Output: 2 Explanation: The following are the substrings of num of length k: - "24" from "240": 24 is a divisor of 240. - "40" from "240": 40 is a divisor of 240. Therefore, the k-beauty is 2.
Example 2:
1 2 3 4 5 6 7 8 9
Input: num = 430043, k = 2 Output: 2 Explanation: The following are the substrings of num of length k: - "43" from "430043": 43 is a divisor of 430043. - "30" from "430043": 30 is not a divisor of 430043. - "00" from "430043": 0 is not a divisor of 430043. - "04" from "430043": 4 is not a divisor of 430043. - "43" from "430043": 43 is a divisor of 430043. Therefore, the k-beauty is 2.
Example 3:
1 2 3 4
Input: s = "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
筆記
這題很明顯的告訴你他用到 Sliding Window
並且思路也不難,基本上算是練手題。
設定 window 左邊,右邊基本上就是左邊 + k ,所以也不用設。
把每個當下的 window 拿出來跟 num 比,沒有餘數就可以把 count + 1 了
程式碼
java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicintdivisorSubstrings(int num, int k) { StringnumString= String.valueOf(num); intleft=0; intwindow=0; intcount=0;
while (left + k < numString.length() + 1) { for (inti= left; i < left + k; i++) { window = window * 10 + Integer.parseInt(String.valueOf(numString.charAt(i))); } if (window != 0 && num % window == 0) count++; left++; window = 0; } return (count); }
TS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
functiondivisorSubstrings(num: number, k: number): number { let left = 0; letwindow: number = 0; let count = 0;
while ((left + k) < num.toString().length + 1) { for (let i = left; i < (left + k); i++) { window = window * 10 + parseInt(num.toString().charAt(i)); } if (num % window === 0) count++; console.log(window); left++; window = 0; } return count; };