Improve Zig Zag conversion#13
Open
ChocolateLoverRaj wants to merge 1 commit intojusexton:mainfrom
Open
Conversation
Single allocation, no reallocations This takes advantage of each character always being 1 byte, which is guaranteed by the LeetCode constraints.
Owner
|
Hey @ChocolateLoverRaj! Thanks for the allocation improvement. Once the linting issues are fixed it would also be nice to reuse the logic for the top and bottom rows. Something like this: fn append(o: &mut String, bytes: &[u8], start: usize, step: usize) {
let mut i = 0;
while let Some(&c) = bytes.get(start + i * step) {
o.push(c as char);
i += 1;
}
}
let num_rows = num_rows as usize;
let bytes = s.as_bytes();
let step = match num_rows {
1 => 1,
n => n * 2 - 2,
};
let mut o = String::with_capacity(s.len());
// Top row
append(&mut o, bytes, 0, step);
// Middle row
// Bottom row
if num_rows > 1 {
append(&mut o, bytes, num_rows - 1, step);
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Single allocation, no reallocations
This takes advantage of each character always being 1 byte, which is guaranteed by the LeetCode constraints.
Instead of actually constructing a zigazag this code just finds the Math pattern behind every row to construct the final output.