文章目錄
- [5918. 統計字串中的元音子字串](https://leetcode-cn.com/problems/count-vowel-substrings-of-a-string/)
- 題解
- [5919. 所有子字串中的元音](https://leetcode-cn.com/problems/vowels-of-all-substrings/)
- [5920. 分配給商店的最多商品的最小值](https://leetcode-cn.com/problems/minimized-maximum-of-products-distributed-to-any-store/)
5918. 統計字串中的元音子字串
題解
【暴力解題】
以每個字符為起始點,然后向后遍歷不同長度子串是否是元音字母:
- 如果不是元音,停止此輪判斷,子串起點右移;
- 如果是元音,判斷子串是否已經包含5種元音,如果有,計數加一,
class Solution {
public int countVowelSubstrings(String word) {
int cnt = 0;
int n = word.length();
String yy = "aeiou";
for (int i = 0; i < n; i++) {
HashSet<Character> set = new HashSet<>();
for (int j = i; j < n; j++) {
if (yy.indexOf(word.charAt(j)) < 0) { // 不是元音
break;
}
set.add(word.charAt(j)); // 將元音加入集合
if (set.size() == 5) { // 全部5種
cnt++;
}
}
}
return cnt;
}
}
5919. 所有子字串中的元音
對于某個元音字母 w o r d [ i ] word[i] word[i],包含該字符的子串 w o r d [ l e f t , r i g h t ] word[left, right] word[left,right],其中 l e f t left left的范圍取值有 0... i 0...i 0...i, r i g h t right right的取值范圍有 i . . . n ? 1 i...n-1 i...n?1,所以,包含字符 w o r d [ i ] word[i] word[i]的子串個數有 ( i + 1 ) ? ( n ? i ) (i+1)*(n-i) (i+1)?(n?i),
class Solution {
public long countVowels(String word) {
int n = word.length();
long res = 0;
String yy = "aoeiu";
for (int i = 0; i < n; i++) {
if (yy.indexOf(word.charAt(i)) >= 0) {
// 左 * 右
res += ((long)i + 1) * ((long)n - i);
}
}
return res;
}
}
5920. 分配給商店的最多商品的最小值
二分法,
class Solution {
public int minimizedMaximum(int n, int[] quantities) {
int left = 1, right = 100000;
while (left < right) {
int mid = (left + right) / 2; // 每個商店分配mid個
int shop = 0; // 店鋪數
for (int q : quantities) {
shop += Math.ceil(1.0 * q / mid);
}
if (shop > n) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/352140.html
標籤:其他
