栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Java&C++题解与拓展——leetcode942.增减字符串匹配【么的新知识】

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java&C++题解与拓展——leetcode942.增减字符串匹配【么的新知识】

每日一题做题记录,参考官方和三叶的题解

目录
  • 题目要求
  • 思路:贪心
    • Java
    • C++
    • Rust
  • 总结

题目要求

思路:贪心
  • 每次都用当前区间内的边界构造,即看到I,就放当前可用的最小值;看到D,就放当前可用的最大值。
  • 证明:
    • 起始区间为 [ 0 , n ] [0,n] [0,n], n n n为所给string大小;
    • 当 s [ 0 ] = I s[0]=I s[0]=I时,填入左边界 0 0 0(最小值),区间变为 [ 1 , n ] [1,n] [1,n],即后续所有数都将比当前大,符合题意;
    • 当 s [ 1 ] = D s[1]=D s[1]=D时,填入右边界 n n n(最大值),区间变为 [ 1 , n − 1 ] [1,n-1] [1,n−1],即后续所有数都将比当前小,符合题意。
Java
class Solution {
    public int[] diStringMatch(String s) {
        int n = s.length(), small = 0, large = n, idx = 0;
        int[] res = new int[n + 1];
        for(int i = 0; i < n; i++) {
            if(s.charAt(i) == 'I') // 放最小的
                res[idx++] = small++;
            else // 放最大的
                res[idx++] = large--;
        }
        res[idx] = small;
        return res;
    }
}
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)
C++
class Solution {
public:
    vector diStringMatch(string s) {
        int n = s.size(), small = 0, large = n, idx = 0;
        vector res(n + 1);
        for(int i = 0; i < n; i++) {
            if(s[i] == 'I') // 放最小的
                res[idx++] = small++;
            else // 放最大的
                res[idx++] = large--;
        }
        res[idx] = small;
        return res;
    }
};
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)
Rust
impl Solution {
    pub fn di_string_match(s: String) -> Vec {
        let mut res = vec![0; s.len() + 1];
        let (mut small, mut large) = (0, s.len() as i32);

        s.chars().enumerate().for_each(|(i, b)| if b == 'I' { // 放最小的
            res[i] = small;
            small += 1
        } else { // 放最大的
            res[i] = large;
            large -= 1
        });
        res[s.len()] = small;
        res
    }
}
总结

快乐开贪,光速完成~


欢迎指正与讨论!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/869901.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号