当前位置:   article > 正文

C++笔试强训day13

C++笔试强训day13

目录

1.⽜⽜冲钻五

2.最长无重复子数组

​编辑

3.重排字符串


1.⽜⽜冲钻五

链接

简单逻辑题,按照题目意思模拟就能过。

详细代码:

  1. #include <iostream>
  2. using namespace std;
  3. int n,k;
  4. void solve()
  5. {
  6. cin >> n >> k;
  7. string s;
  8. cin >> s;
  9. int sum = 0;
  10. int cnt = 0;
  11. for(int i = 0; i < s.size(); i++)
  12. {
  13. if(s[i] == 'W')
  14. {
  15. if(cnt >= 2)
  16. {
  17. sum += k;
  18. }
  19. else
  20. {
  21. sum += 1;
  22. }
  23. cnt++;
  24. }
  25. else
  26. {
  27. sum -= 1;
  28. cnt = 0;
  29. }
  30. }
  31. cout << sum << endl;
  32. }
  33. int main()
  34. {
  35. int t;
  36. cin >> t;
  37. while(t--)
  38. solve();
  39. return 0;
  40. }

2.最长无重复子数组

链接

这种题目一眼双指针,然后晋升为滑动窗口解题:

注意进窗口和出窗口的位置以及len的更新就能AC。

  1. // 哈希+双指针
  2. class Solution {
  3. public:
  4. int cnt[100010] = { 0 };
  5. int maxLength(vector<int>& arr) {
  6. int n = arr.size();
  7. int l = 0;
  8. int r = 0;
  9. int len = 0;
  10. while(r < n)
  11. {
  12. cnt[arr[r]]++;// 进窗口
  13. while(cnt[arr[r]] > 1)// 出窗口(条件)
  14. {
  15. cnt[arr[l]]--;
  16. l++;
  17. }
  18. len = max(len, r - l + 1);
  19. r++;
  20. }
  21. return len;
  22. }
  23. };

3.重排字符串

链接

找到填入规律就很好办,先找到次数最多的字母,隔空填入:

(例如)

然后将剩下的字母依次填入即可,注意一个细节即可:

当超出范围时,记得将填入位置的下标修改为1

还有就是要会判断是否能重排的临界:


如上图,若是多出一个C,必然不可能重排,即C的数量 >(n + 1) /  2的话,直接输出noi就行了。

否则,考虑后者。

详细代码:

  1. #include <iostream>
  2. using namespace std;
  3. const int N = 100010;
  4. int n;
  5. char s[N];
  6. char ret[N];
  7. int main()
  8. {
  9. cin >> n >> s;
  10. int cnt[26] = { 0 }; // 统计每个字符的频次
  11. int maxIndex, maxCount = 0;
  12. for (int i = 0; i < n; i++)
  13. {
  14. if (maxCount < ++cnt[s[i] - 'a'])
  15. {
  16. maxCount = cnt[s[i] - 'a'];
  17. maxIndex = s[i] - 'a';
  18. }
  19. }
  20. if (maxCount > (n + 1) / 2)
  21. cout << "no" << endl;
  22. else
  23. {
  24. cout << "yes" << endl;
  25. int index = 0;
  26. // 先去摆放出现次数最多的
  27. while (maxCount--)
  28. {
  29. ret[index] = maxIndex + 'a';
  30. index += 2;
  31. }
  32. // 处理剩下的
  33. for (int i = 0; i < 26; i++)
  34. {
  35. if (cnt[i] && i != maxIndex)
  36. {
  37. while (cnt[i]--)
  38. {
  39. if (index >= n) index = 1;
  40. ret[index] = i + 'a';
  41. index += 2;
  42. }
  43. }
  44. }
  45. // 打印结果
  46. for (int i = 0; i < n; i++) cout << ret[i];
  47. cout << endl;
  48. }
  49. return 0;
  50. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/563534
推荐阅读
相关标签
  

闽ICP备14008679号