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()
}
}


This account has disabled anonymous posting.
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

Profile

amarao: (Default)
amarao

April 2026

S M T W T F S
   1234
567 891011
12131415161718
19202122232425
2627282930  

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Apr. 12th, 2026 11:41 pm
Powered by Dreamwidth Studios