Day63.算法训练

3. 无重复字符的最长子串

class Solution {
    public int lengthOfLongestSubstring(String s) {

        char[] chars = s.toCharArray();

        int max = 0;

        Map map = new HashMap<>();

        int i = 0;

        for (int j = 0; j < chars.length; j++) {
            if (map.containsKey(chars[j])) {
                Integer del = map.get(chars[j]);
                i = Integer.max(i, del + 1);
            }
            int len = j - i + 1;
            max = Integer.max(max, len);
            map.put(chars[j], j);
        }
        return max;
    }
}

2. 两数相加

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode dummyHead = new ListNode(-1);
        ListNode p3 = dummyHead;
        int carry = 0;
        while (p1 != null && p2 != null) {
            int sum = p1.val + p2.val + carry;
            if (sum >= 10) {
                carry = 1;
                sum = sum - 10;
            } else {
                carry = 0;
            }
            p3.next = new ListNode(sum);
            p1 = p1.next;
            p2 = p2.next;
            p3 = p3.next;
        }

        while (p1 != null) {
            int sum = p1.val + carry;
            if (sum >= 10) {
                sum = sum - 10;
                carry = 1;
            } else {
                carry = 0;
            }
            p3.next = new ListNode(sum);
            p1 = p1.next;
            p3 = p3.next;
        }

        while (p2 != null) {
            int sum = p2.val + carry;
            if (sum >= 10) {
                sum = sum - 10;
                carry = 1;
            } else {
                carry = 0;
            }
            p3.next = new ListNode(sum);
            p2 = p2.next;
            p3 = p3.next;
        }

        if (carry == 1) {
            p3.next = new ListNode(carry);
        }
        return dummyHead.next;
    }
}

你可能感兴趣的:(算法)