Practicing Rust – Swapping Vowels

Hi, everyone,This is the Practicing Rust column.

Today, let’s look at a small case: swapping vowels.

Practicing Rust - Swapping Vowels

Question

Given a string <span>s</span>, swap all the vowels in the string and return the resulting string.

The vowels include <span>'a'</span>, <span>'e'</span>, <span>'i'</span>, <span>'o'</span>, <span>'u'</span>, <span>'A'</span>, <span>'E'</span>, <span>'I'</span>, <span>'O'</span>, <span>'U'</span>.

Example: input: “hello” output: “holle”

input: leetcode output: leotcede

Template:

pub fn reverse_vowels(s: String) -> String {
}

Analysis

According to the problem statement, we only need to find the first pair of vowels from both ends and swap them, then shrink towards the center, continuing this process will solve the problem.

Solution

pub fn reverse_vowels(s: String) -> String {

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

    let mut i = 0;
    let mut j = chars.len() - 1;

    while i < j {

        if !matches!(chars[i],'a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E' | 'I' | 'O' | 'U') {
            i += 1;
            continue;
        }

        if !matches!(chars[j],'a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E' | 'I' | 'O' | 'U') {
            j -= 1;
            continue;
        }

        chars.swap(i,j);

        i += 1;
        j -= 1;
    }

    String::from_iter(chars)
}

Tricks

  1. Convert the <span>String</span> type to a <span>char</span> array using <span>String.chars().collect()</span>.
  2. <span>char</span> array to <span>String</span>, use <span>String::from_iter(chars)</span>.
  3. <span>match</span> expression has a macro definition <span>matches!</span> which is very convenient; if the match is successful, it returns <span>true</span> or <span>false</span>.

Leave a Comment