第一周

2022-10-11

1404. Number of Steps to Reduce a Number in Binary Representation to One

impl Solution {
     pub fn num_steps(s: String) -> i32 {
        let s = &mut Vec::from(s);
        let mut res = 0;
        while !(s.len() == 1 && s[0] == '1' as u8) {
            if s[s.len() - 1] == '1' as u8 {
                Self::jump(s, s.len() - 1);
            } else {
                s.pop();
            }
            res += 1;
        }
        res
    }
    pub fn jump(s: &mut Vec<u8>, index: usize) {
        s[index] = '0' as u8;
        for i in (0..index).rev() {
            if s[i] == '1' as u8 {
                s[i] = '0' as u8;
            } else {
                s[i] = '1' as u8;
                return;
            }
        }
        s[0] = '0' as u8;
        s.insert(0, '1' as u8);
    }
}

1405. Longest Happy String

impl Solution {
    pub fn longest_diverse_string(mut a: i32, mut b: i32, mut c: i32) -> String { 
        let mut v = String::new();
        let (mut a_use, mut b_use, mut c_use) = (0, 0, 0);
        let total = a + b + c;
        for _ in (0..total) {
            if (a >= b && a >= c && a_use != 2) || (b_use == 2 && a > 0) || (c_use == 2 && a > 0) {
                v.push('a');
                a_use += 1;
                a -= 1;
                b_use = 0;
                c_use = 0;
            } else if (b >= a && b >= c && b_use != 2)
                || (a_use == 2 && b > 0)
                || (c_use == 2 && b > 0)
            {
                v.push('b');
                b_use += 1;
                b -= 1;
                a_use = 0;
                c_use = 0;
            } else if (c >= a && c >= b && c_use != 2)
                || (a_use == 2 && c > 0)
                || (b_use == 2 && c > 0)
            {
                v.push('c');
                c_use += 1;
                c -= 1;
                a_use = 0;
                b_use = 0;
            }
        }
        v
    }
}

6. Zigzag Conversion

impl Solution {
    pub fn convert(s: String, num_rows: i32) -> String {
        if num_rows == 1 || s.len() < num_rows as usize {
            return s;
        }
        let num_rows = num_rows as usize;

        let col = s.len();

        // println!("row: {}, col: {}", num_rows, col);

        let mut str_arr: Vec<Vec<char>> = (0..=num_rows).map(|_| vec![0 as char; col]).collect();

        let chars: Vec<char> = s.chars().collect();
        // i is down
        // j is right
        let (mut i, mut j) = (1, 1);
        let mut index = 0;
        let mut down = true;
        let mut right = false;
        while index < s.len() {
            // touch the bottom
            // then move rigth
            println!("{}, {}", i, j);
            str_arr[i][j] = chars[index];

            if down {
                i += 1;
            }

            if right {
                i -= 1;
                j += 1;
            }

            if i == num_rows as usize {
                down = false;
                right = true;
            }
            if i == 1 {
                right = false;
                down = true;
            }

            index += 1;
        }
        let mut s = String::new();
        for row in str_arr.iter() {
            // println!("{row:?}");
            for c in row.iter() {
                if *c != 0 as char {
                    s.push(*c);
                }
            }
        }
        s
    }
}

面试题 03.03. Stack of Plates LCCI

#[derive(Debug)]
pub struct StackOfPlates {
    data: Vec<Vec<i32>>,
    cap: i32,
}

#[allow(unused)]
impl StackOfPlates {
    pub fn new(cap: i32) -> Self {
        StackOfPlates {
            data: Vec::new(),
            cap: cap,
        }
    }
    pub fn push(&mut self, val: i32) {
        if self.cap <= 0 {
            return;
        }
        let last = self.data.last_mut();
        if let Some(v) = last {
            if v.len() < self.cap as usize {
                v.push(val);
                return;
            }
        }
        let mut stack = Vec::with_capacity(self.cap as usize);
        stack.push(val);
        self.data.push(stack);
    }
    pub fn pop(&mut self) -> i32 {
        let last = self.data.last_mut();
        if let Some(v) = last {
            if let Some(val) = v.pop() {
                if v.is_empty() {
                    self.data.pop();
                }
                return val;
            }
        }
        -1
    }
    pub fn pop_at(&mut self, index: i32) -> i32 {
        let stack = self.data.get_mut(index as usize);
        if let Some(v) = stack {
            if let Some(val) = v.pop() {
                if v.is_empty() {
                    self.data.remove(index as usize);
                }
                return val;
            }
        }
        -1
    }
}

24. Swap Nodes in Pairs

// Definition for singly-linked list.
// #[derive(PartialEq, Eq, Clone, Debug)]
// pub struct ListNode {
//   pub val: i32,
//   pub next: Option<Box<ListNode>>
// }
//
// impl ListNode {
//   #[inline]
//   fn new(val: i32) -> Self {
//     ListNode {
//       next: None,
//       val
//     }
//   }
// }
impl Solution {
    pub fn swap_pairs(head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        let mut prev = head;
        let mut result = ListNode::new(0);
        let mut tail = &mut result;
        while let Some(mut first) = prev {
            prev = first.next.take();
            if let Some(mut second) = prev {
                prev = second.next.take();
                second.next = Some(first);
                tail.next = Some(second);
                tail = tail.next.as_mut().unwrap().next.as_mut().unwrap();
            } else {
                tail.next = Some(first);
                tail = tail.next.as_mut().unwrap();
            }
        }
        result.next
    }
}

1685. Sum of Absolute Differences in a Sorted Array

impl Solution {
    pub fn get_sum_absolute_differences(nums: Vec<i32>) -> Vec<i32> {
        let mut prefix_array: Vec<i32> = Vec::with_capacity(nums.len());
        let mut result: Vec<i32> = Vec::with_capacity(nums.len());
        prefix_array.push(nums[0]);
        for i in 1..nums.len() {
            prefix_array.push(prefix_array[i - 1] + nums[i]);
        }
        for i in 0..nums.len() {
            result.push((i as i32 + 1) * nums[i] - prefix_array[i]
                + (prefix_array[nums.len() - 1] - prefix_array[i])
                - nums[i] * (nums.len() as i32 - 1 - i as i32));
        }
        result
    }
}

面试题 01.05. One Away LCCI

impl Solution {
    pub fn one_edit_away(first: String, second: String) -> bool {
        let max_str: &String;
        let min_str: &String;
        if first.len() > second.len() {
            max_str = &first;
            min_str = &second;
        } else {
            max_str = &second;
            min_str = &first;
        }

        let point = first.len().max(second.len()) - first.len().min(second.len());
        if point >= 2 {
            return false;
        }
        let char1: Vec<_> = min_str.bytes().collect();
        let char2: Vec<_> = max_str.bytes().collect();

        match point {
            // must replace
            0 => {
                let mut diff = 0;
                for i in 0..first.len() {
                    if char1[i] != char2[i] {
                        diff += 1;
                    }
                }
                if diff == 1 || diff == 0 {
                    return true;
                } else {
                    return false;
                }
            }
            // must insert or remove
            1 => {
                let mut index = -1;
                for i in 0..char1.len() {
                    if char1[i] != char2[i] {
                        index = i as i32;
                        break;
                    }
                }
                // means need insert in short string
                if index == -1 {
                    return true;
                } else {
                    let i = index as usize;
                    return char1[i..] == char2[i + 1..];
                }
                // if index + 1 >= char2.len() {
                //     return true;
                // }
                // true
            }
            _ => false,
        }
    }
}
leetcode