carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode1309:解码字母到整数映射(decrypt-string-from-alphabet-to-integer-mapping) #205

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个字符串 s,它由数字('0' - '9')和 '#' 组成。我们希望按下述规则将 s 映射为一些小写英文字符:

字符('a' - 'i')分别用('1' - '9')表示。 字符('j' - 'z')分别用('10#' - '26#')表示。  返回映射之后形成的新字符串。

题目数据保证映射始终唯一。

 

示例 1:

输入:s = "10#11#12" 输出:"jkab" 解释:"j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".

示例 2:

输入:s = "1326#" 输出:"acz"  

提示:

1 <= s.length <= 1000 s[i] 只包含数字('0'-'9')和 '#' 字符。 s 是映射始终存在的有效字符串。

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/decrypt-string-from-alphabet-to-integer-mapping

carloscn commented 1 year ago

问题分析

准备一个字母表,1 -> a 2 -> b

从后向前遍历,当前字符是:

pub fn freq_alphabets(s: String) -> String
{
    let mut ret:String = String::new();
    let mut s_vec:Vec<char> = vec![];
    let mut char_vec:Vec<char> = vec![];

    let dup:Vec<char> = s.chars().into_iter().collect();

    for i in 'a'..'z' {
        char_vec.push(i);
    }
    char_vec.push('z');

    let mut i:usize = 0;
    while i < dup.len() {
        let mut num;
        if dup[dup.len() - i - 1] != '#' {
            num = (dup[dup.len() - i - 1] as u8 - '0' as u8) as usize;
            i += 1;
        } else {
            num = (dup[dup.len() - i - 3] as u8 - '0' as u8) as usize * 10;
            num += (dup[dup.len() - i - 2] as u8 - '0' as u8) as usize;
            i += 3;
        }
        s_vec.insert(0, char_vec[num - 1]);
    }

    let s_str:String = s_vec.into_iter().collect();
    ret.push_str(&s_str);

    return ret;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/553300 https://github.com/carloscn/structstudy/commit/65573ce0961bd104e181f29e96073766f98b8cf3