牛客小白赛 / leetcode双周赛:
知识点总结:
1.__builtin_popcount(r),算数字里有几个1
class Solution { public: vector<int> sortByBits(vector<int>& arr) { sort(arr.begin(), arr.end(), [](int l, int r) { int ln = __builtin_popcount(l); int rn = __builtin_popcount(r); if (ln != rn) return ln < rn; return l < r; }); return arr; } };
2.若直接计算数字中1的个数,可以用取余,除法来算
3.在类外直接写比较函数,加const &
4.第三题题解
后面的题不要抱有幻想,一定要用DP DFS/BFS之类的做,不要尝试暴力
1358. Number of Substrings Containing All Three Characters
- User Accepted:958
- User Tried:1490
- Total Accepted:1003
- Total Submissions:2820
- Difficulty:Medium
Given a string s
consisting only of characters a, b and c.
Return the number of substrings containing at least one occurrence of all these characters a, b and c.
Example 1:
Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again).
Example 2:
Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb".
Example 3:
Input: s = "abc" Output: 1
Constraints:
3 <= s.length <= 5 x 10^4
s
only consists of a, b or c characters.
//sequence "abcabc" find substring contain 'a','b','c' class Solution { public: int numberOfSubstrings(string s) { int n = s.size(); //two-dimension vector store range vector<vector<int> > dp(3, vector<int>(n + 1, -1)); //store the nearest index of appearance a b c for (int i = n - 1; i >= 0; i--) { //no new appear record past for (int j = 0; j < 3; j++) dp[j][i] = dp[j][i + 1]; //has new flush dp[s[i] - 'a'][i] = i; } long long ans = 0; for (int i = 0; i < n; i++) { bool ok = true; //if has -1 means lack of val for (int j = 0; j < 3; j++) { if (dp[j][i] == -1) ok = false; } //if ensure have three kinds calc the max distance to end if (ok) { int mx = -1; for (int j = 0; j < 3; j++) mx = max(mx, dp[j][i]); ans += n - mx; } } return ans; } };