<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;
    }
}







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值