Project Leet Code 22Spring

One leetcode a day, keeps my code great. :)

1. Two Sum

impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        use std::collections::HashMap;
        let mut map = HashMap::new();
        for (index, num) in nums.iter().enumerate() {
            let index = index as i32;
            if let Some(&index_2) = map.get(&(target - num)) {
                return vec![index, index_2];
            }
            map.insert(num, index);
        }
        vec![]
    }
}

2. δΈ€ζ•°η›ΈεŠ 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if (l1 == nullptr && l2 == nullptr) {
            ListNode *result = new ListNode();
            return result;
        }
        ListNode head = ListNode();
        ListNode *curr = &head;
        int carry = 0;
        while (l1 || l2) {
            int node = 0;
            if (l1 != nullptr) {
                node += l1->val;
                l1 = l1->next;
            }
            if (l2 != nullptr) {
                node += l2->val;
                l2 = l2->next;
            }
            node += carry;

            carry = node / 10;
            node = node % 10;

            curr->next = new ListNode(node);
            curr = curr->next;
        }

        if (carry) {
            curr->next = new ListNode(1);
        }

        return head.next;
    }
};

3. ζ— ι‡ε€ε­—η¬¦ηš„ζœ€ι•Ώε­δΈ²

inline int max(int a, int b) {
    return a > b? a : b;
}

int lengthOfLongestSubstring(char * s){
    if (*s == '\0') {
        return 0;
    }

    int last_index[256];
    int last = -1;
    int result = 1;

    for (int i = 0; i < 256; i++) {
        last_index[i] = -1;
    }

    int index = 0;
    while (*s != '\0') {
        char c = *s;
        last = max(last, last_index[c]);
        result = max(index - last, result);
        last_index[c] = index;
        s ++;
        index ++;
    }
    return result;
}

4.