Skip to main content
Back to problems
#1417
Easy Algorithms

Reformat the string

String
52.1% acceptance
Feb 25, 2026
618
110
You are given an alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn reformat(s: String) -> String {
    let mut digits: Vec<char> = s.chars().filter(|c| c.is_ascii_digit()).collect();
    let mut letters: Vec<char> = s.chars().filter(|c| c.is_ascii_alphabetic()).collect();
    if digits.len().abs_diff(letters.len()) > 1 { return String::new(); }
    if letters.len() > digits.len() { std::mem::swap(&mut digits, &mut letters); }
    let mut result = String::new();
    for (d, l) in digits.iter().zip(letters.iter()) {
      result.push(*d);
      result.push(*l);
    }
    if digits.len() > letters.len() { result.push(*digits.last().unwrap()); }
    result
  }
}