<Java算法实现--LeetCode(2)(3)>2017-11-21

<1>问题描述

SOURCE : LeetCode(2)

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example :

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Answer:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode listNode = new ListNode(0);
        //全为空,返回0
        if(l1 == null && l2 == null){
            return listNode;
        }
        //结束条件全为空时,否则继续,空的为0,非空用val,低位数通过next赋回来,进位数carry
        int carry = 0;
        int sum = 0;
        ListNode car = listNode;
        while(l1 != null || l2 != null){
            int ln1 = l1 == null ? 0 : l1.val;
            int ln2 = l2 == null ? 0 : l2.val;
            sum = ln1 + ln2 + carry;
            car.next = new ListNode(sum%10);
            car = car.next;
            carry = sum/10;
            l1 = l1 == null ? null : l1.next;
            l2 = l2 == null ? null : l2.next;
        }
        //next是car的传导过程结果,勿忘赋值
        if(carry != 0){
            car.next = new ListNode(carry);
        }
        //.next是因为原来是0啊,next才是car,真正的结果
        return listNode.next;
    }
}


<2>问题描述

SOURCE : LeetCode(3)

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

A nsw er:

/*将字符串每个字符存入hashmap中。设定两个指针,i用来遍历字符串,当遍历到与之前重复的字符时,将j移动到
*该重复字符的右边,然后i字符到j字符的长度max,对应着最大的max的substring(j,i)就是所求,这里根据题目
*要求只将max返回
*/
class Solution {
    public int lengthOfLongestSubstring(String s) {
        if(s.length() == 0)
            return 0;
        int max = 0;
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i = 0, j = 0; i < s.length(); i++){
            if(map.containsKey(s.charAt(i))){
                j = Math.max(j, map.get(s.charAt(i))+1);
            }
            map.put(s.charAt(i), i);
            max = Math.max(max, i-j+1);
        }
        return max;
    }
}







猜你喜欢

转载自blog.csdn.net/adelaide_guo/article/details/78594355