每日一题——LeetCode1422.分割字符串的最大得分

方法一 暴力枚举

枚举所有分割点的情况,取最大得分

var maxScore = function(s) {
    let res = 0;
    const n = s.length;
    for (let i = 1; i < n; i++) {
        let score = 0;
        for (let j = 0; j < i; j++) {
            if (s[j] === '0') {
                score++;
            }
        }
        for (let j = i; j < n; j++) {
            if (s[j] === '1') {
                score++;
            }
        }
        res = Math.max(res, score);
    }
    return res;
};

 消耗时间和内存情况:

方法二 两次遍历:

第一次遍历找出1的数量,第二次循环找所以分割点,如果把0分到左边,左边分数+1,右边不变,把1分到左边,左边分数不变,右边分数-1,看左右分数之和是否大于max

var maxScore = function(s) {
    let max=-1,score0=0,score1=0
    for(let char of s){
        if(char==='1'){
            score1++
        }
    }
    if(score1===0) return s.length-1
    for(let i=0 ;i<s.length-1;i++){
        if(s[i]==='0'){
            score0++
        }else{
            score1--
        }
        if(score0+score1>max){
            max=score0+score1
        }
    }
    return max
};

 消耗时间和内存情况:

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-08 07:08:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-08 07:08:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-08 07:08:01       87 阅读
  4. Python语言-面向对象

    2024-02-08 07:08:01       96 阅读

热门阅读

  1. 每天一个数据分析题(一百五十五)

    2024-02-08 07:08:01       60 阅读
  2. [缓存] - Redis

    2024-02-08 07:08:01       54 阅读
  3. SpringCache缓存快速实现注解

    2024-02-08 07:08:01       48 阅读
  4. Vscode SSH使用云服务器访问内网主机

    2024-02-08 07:08:01       52 阅读
  5. reactive 与 ref 的区别

    2024-02-08 07:08:01       55 阅读
  6. 项目中常用的一些数据库及缓存

    2024-02-08 07:08:01       48 阅读