carloscn / structstudy

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

leetcode917: 仅仅反转字母(reverse-only-letters) #164

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个字符串 s ,根据下述规则反转字符串:

所有非英文字母保留在原有位置。 所有英文字母(小写或大写)位置反转。 返回反转后的 s 。

示例 1:

输入:s = "ab-cd" 输出:"dc-ba" 示例 2:

输入:s = "a-bC-dEf-ghIj" 输出:"j-Ih-gfE-dCba" 示例 3:

输入:s = "Test1ng-Leet=code-Q!" 输出:"Qedo1ct-eeLg=ntse-T!"   提示

1 <= s.length <= 100 s 仅由 ASCII 值在范围 [33, 122] 的字符组成 s 不含 '\"' 或 '\'

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/reverse-only-letters

carloscn commented 1 year ago

问题分析

准备一个vec,用于容纳返回的字符串。准备两个index变量,一个叫做left_index, right_index。遍历字符串:

  1. left_index找到合法的置换位置:if ret_vec[left_index] 是大写或者小写字母;不是的话往后循环,直到找到这个为止。
  2. right_index找到合法的置换位置:if ret_vet[rigth_index] 是大写或者小写的字母的话;不是的话往前循环,直到找到这个为止位置。注意left不能大于right。
  3. 置换left和right的字符串的位置。
  4. 直到left >= right
pub fn reverse_only_letters(s: String) -> String
{
    let mut ret_str:String = String::new();
    let mut left_index:usize = 0;
    let mut right_index:usize = s.len();
    let mut ret_chars:Vec<char> = s.chars().collect();
    if right_index < 1 {
        return ret_str;
    }
    right_index -= 1;
    while left_index < right_index {
        while !ret_chars[left_index].is_alphabetic() &&
              left_index < right_index {
            left_index += 1;
        }
        while !ret_chars[right_index].is_alphabetic() &&
            left_index < right_index {
            right_index -= 1;
        }
        if left_index < right_index {
            ret_chars.swap(left_index, right_index);
            left_index += 1;
            right_index -= 1;
        }
    }
    let s:String = ret_chars.into_iter().collect();
    ret_str.push_str(&s);
    return ret_str;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/551603 https://github.com/carloscn/structstudy/commit/3e3139e95cb6db80b9cb77c52474ff179325fd8c