1663.具有给定数值的最小字符串
链接:1663.具有给定数值的最小字符串
难度:Medium
标签:贪心、字符串
简介:给你两个整数 n 和 k 。返回 长度 等于 n 且 数值 等于 k 的 字典序最小 的字符串。
题解 1 - rust
- 编辑时间:2023-01-27
- 执行用时:4ms
- 内存消耗:2MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn greatest_letter(s: String) -> String {
        let s = s.chars().collect::<Vec<char>>();
        let mut ans = 0usize;
        let mut map = [0; 128];
        for c in s {
            map[c as usize] += 1;
            let upper_c = c.to_uppercase().next().unwrap() as usize;
            let lower_c = c.to_lowercase().next().unwrap() as usize;
            if map[upper_c] > 0 && map[lower_c] > 0 && ans < upper_c {
                ans = upper_c;
            }
        }
        if ans == 0 {
            "".to_string()
        } else {
            String::from(ans as u8 as char)
        }
    }
}
题解 2 - python
- 编辑时间:2023-01-27
- 执行用时:56ms
- 内存消耗:15MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
def greatestLetter(self, s: str) -> str:
    ans = ""
    sset = set()
    for i, c in enumerate(s):
        sset.add(c)
        if c.isupper() and c.lower() in sset and (ans == "" or ans[0] < c) or c.islower() and c.upper() in sset and (ans == "" or ans[0] < c.upper()):
             ans = c.upper()
    return ans
题解 3 - cpp
- 编辑时间:2023-01-27
- 执行用时:8ms
- 内存消耗:6.4MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    string greatestLetter(string s) {
        string ans = "";
        int map[128] = {0};
        for (auto &c : s) {
            map[c]++;
            if (isupper(c) && map[tolower(c)] && (ans == "" || ans[0] < c) ||
                islower(c) && map[toupper(c)] && (ans == "" || ans[0] < toupper(c))) ans = toupper(c);
        }
        return ans;
    }
};