917. Reverse Only Letters

Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

 

Example 1:

Input: "ab-cd"
Output: "dc-ba"

Example 2:

Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

 

Note:

  1. S.length <= 100
  2. 33 <= S[i].ASCIIcode <= 122 
  3. S doesn't contain \ or "

Rust Solution

struct Solution;

impl Solution {
    fn reverse_only_letters(s: String) -> String {
        let n = s.len();
        if n == 0 {
            return "".to_string();
        }
        let mut a: Vec<char> = s.chars().collect();
        let mut i = 0;
        let mut j = n - 1;
        while i < j {
            while i < j && !a[i].is_alphabetic() {
                i += 1;
            }
            while i < j && !a[j].is_alphabetic() {
                j -= 1;
            }
            if i < j {
                a.swap(i, j);
            }
            i += 1;
            j -= 1;
        }
        a.iter().collect()
    }
}

#[test]
fn test() {
    let s = "ab-cd".to_string();
    let t = "dc-ba".to_string();
    assert_eq!(Solution::reverse_only_letters(s), t);
    let s = "a-bC-dEf-ghIj".to_string();
    let t = "j-Ih-gfE-dCba".to_string();
    assert_eq!(Solution::reverse_only_letters(s), t);
    let s = "Test1ng-Leet=code-Q!".to_string();
    let t = "Qedo1ct-eeLg=ntse-T!".to_string();
    assert_eq!(Solution::reverse_only_letters(s), t);
}

Having problems with this solution? Click here to submit an issue on github.