amarao: (Default)
[personal profile] amarao
Некоторые задачи на leetcode доставляют трушное настоящее удовольствие.

https://leetcode.com/problems/break-a-palindrome/

Given a palindromic string of lowercase English letters palindrome, replace exactly one character with any lowercase English letter so that the resulting string is not a palindrome and that it is the lexicographically smallest one possible.

Return the resulting string. If there is no way to replace a character to make it not a palindrome, return an empty string.

A string a is lexicographically smaller than a string b (of the same length) if in the first position where a and b differ, a has a character strictly smaller than the corresponding character in b. For example, "abcc" is lexicographically smaller than "abcd" because the first position they differ is at the fourth character, and 'c' is smaller than 'd'.

тесткейсы:

"" => ""
"a" => ""
"aa" => "ab"
"zz" => "az"
"aba" => "abb" (самый сложный случай, на котором я сначала попался).

Я получил реальное неиллюзорное удовольствие от языка и от задачи. Я не уверен, что на питоне у меня бы получилось компактнее и выразительнее

pub fn break_palindrome(palindrome: String) -> String {
let mut bytes = palindrome.into_bytes();
let len = bytes.len();
if len < 2 {
String::from("")
} else {
let mid = len / 2;
let odd = (len % 2) == 1;
let last = len - 1;
for (idx, c) in bytes.iter_mut().enumerate() {
match c {
b'a' if idx == last => *c = b'b',
b'a' => {}
_ if odd && idx == mid => {} // mid char, can't change
_ => {
*c = b'a';
break;
}
}
}
String::from_utf8(bytes).unwrap()
}
}


Profile

amarao: (Default)
amarao

February 2026

S M T W T F S
123456 7
8910111213 14
15161718192021
22232425262728

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Feb. 25th, 2026 11:53 am
Powered by Dreamwidth Studios