carloscn / structstudy

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

leetcode1528:重新排列字符串(shuffle-string) #239

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个字符串 s 和一个 长度相同 的整数数组 indices 。

请你重新排列字符串 s ,其中第 i 个字符需要移动到 indices[i] 指示的位置。

返回重新排列后的字符串。

 

示例 1:

image

输入:s = "codeleet", indices = [4,5,6,7,0,2,1,3] 输出:"leetcode" 解释:如图所示,"codeleet" 重新排列后变为 "leetcode" 。

示例 2:

输入:s = "abc", indices = [0,1,2] 输出:"abc" 解释:重新排列后,每个字符都还留在原来的位置上。  

提示:

s.length == indices.length == n 1 <= n <= 100 s 仅包含小写英文字母 0 <= indices[i] < n indices 的所有的值都是 唯一 的

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/shuffle-string

carloscn commented 1 year ago

问题分析

pub fn restore_string(s: String, indices: Vec<i32>) -> String
{
    if s.is_empty() ||
       indices.is_empty() ||
       s.len() != indices.len() {
        return String::new();
    }

    let ret_str:String;
    let mut s_vec:Vec<char> = s.chars().collect();
    let mut ind_dup = indices.clone();

    for j in 0..s_vec.len() {
        for i in 0..s_vec.len() - j - 1 {
            if ind_dup[i] > ind_dup[i + 1] {
                let t = ind_dup[i];
                ind_dup[i] = ind_dup[i + 1];
                ind_dup[i + 1] = t;

                let t = s_vec[i];
                s_vec[i] = s_vec[i + 1];
                s_vec[i + 1] = t;
            }
        }
    }

    ret_str = s_vec.into_iter().collect();

    return ret_str;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/554877 https://github.com/carloscn/structstudy/commit/03635ebc7b783b5b76fdc47f6e7f7615e730acf6