Skip to content

Improve Zig Zag conversion#13

Open
ChocolateLoverRaj wants to merge 1 commit intojusexton:mainfrom
ChocolateLoverRaj:better-zigzag-contribute
Open

Improve Zig Zag conversion#13
ChocolateLoverRaj wants to merge 1 commit intojusexton:mainfrom
ChocolateLoverRaj:better-zigzag-contribute

Conversation

@ChocolateLoverRaj
Copy link
Copy Markdown
Contributor

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.

Single allocation, no reallocations

This takes advantage of each character always being 1 byte, which is
guaranteed by the LeetCode constraints.
@jusexton
Copy link
Copy Markdown
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);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants