Oct. 10th, 2022

amarao: (Default)
Некоторые задачи на 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

May 2026

S M T W T F S
     12
3 4 567 89
101112 13141516
17181920 2122 23
242526 27282930
31      

Most Popular Tags

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated May. 27th, 2026 06:03 pm
Powered by Dreamwidth Studios