链表找环

15

请编写函数,功能为对于一个字符串s,反转其中所有的辅音字母,并返回结果字符串。
举例:
s=“good”
输出:“doog”

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. class Solution {
  5. public:
  6. //判断是否是元音字母
  7. string a = "aeiou";
  8. //大写字母转小写
  9. char my_tolower(char c) {
  10. if(c >= 'A' && c <= 'Z') {
  11. char x = c + 32;
  12. return x;
  13. }
  14. return c;
  15. }
  16. bool check(char c) {
  17. //如果元音字符串中找得到c,返回true
  18. // return a.find(my_tolower(c)) != -1;
  19. return a.find(tolower(c)) != -1;
  20. }
  21. string reverseConsos(string s) {
  22. //双指针
  23. for(int i = 0, j = s.size() - 1; i < j; i ++, j --) {
  24. while(i < j && check(s[i])) i ++;
  25. while(i < j && check(s[j])) j --;
  26. swap(s[i], s[j]);
  27. }
  28. return s;
  29. }
  30. };
  31. int main()
  32. {
  33. Solution s;
  34. string a;
  35. cin >> a;
  36. cout << s.reverseConsos(a) << endl;
  37. }

16

给定整数数组(有正数、有负数),找出总乘积最大的连续数列,返回此最大的总乘积的值。(假设不会产生整数的溢出问题)
函数原型:int findMaxProduct(int *pArr, int arrLen)
举例:
输入:2,-8,3,6,4
输出:18(也就是序列(3,6)的乘积)

DP

  • 状态表示:

f[i]:前i个数中,总乘积最大的连续数列的最大乘积
g[i]:前i个数中,总乘积最小的连续数列的最小乘积

  • 状态计算

f[i]=

只有nums[i] 包括nums[i-1]
nums[i] = 0 nums[i] > 0 nums[i] < 0
nums[i] f[i-1] nums[i]*f[i-1] nums[i]*g[i-1]

g[i]=

只有nums[i] 包括nums[i-1]
nums[i] = 0 nums[i] > 0 nums[i] < 0
nums[i] g[i-1] nums[i]*g[i-1] nums[i]*f[i-1]
  • 时间复杂度 = 状态数量(n)*每个状态转移时间(1) = O(n)

    1. class Solution {
    2. public:
    3. int maxProduct(vector<int>& nums) {
    4. //一维状态f[i],g[i]可以用f,g一个数表示,并都用nums[0]初始化
    5. int f = nums[0], g = nums[0];
    6. int res = nums[0];//记录结果
    7. for(int i = 1; i < nums.size(); i ++)
    8. {
    9. int a = nums[i], fa = a * f, ga = a * g;
    10. f = max(a, max(fa, ga));
    11. g = min(a, min(fa, ga));
    12. res = max(res, f);
    13. }
    14. return res;
    15. }
    16. };