算法练习1


算法练习1

Add TwoNumbers

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.

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

解题思路

题目意思大概就是整数相加,输入是两个反向存储整数的链表,以链表的形式输出两数之和。其实反向存储整数更方便两数相加,进位直接加到下一个节点上。设输入链表为l1、l2,当l1或l2不为空时,进行循环相加对应的位,并作进位处理。循环结束后判断时候仍有进位,若有就加一个进位节点。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode p = l1, q = l2, curr = head;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return head.next;
}

Longest Substring Without Repeating Characters

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.

解题思路

题目意思是求最长不重复子串。我的思路是先求出字符串包含的字母个数num,最长不重复子串的长度必然小于等于num。接下来循环判断子串就好了。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Solution {
public int lengthOfLongestSubstring(String s) {
int[] chars = new int[256];
int res = 0;
for (char c : s.toCharArray()) {
chars[c] = 1;
}
int num = 0;
for (int i = 0; i < 256; i++) {
if (chars[i] != 0) num++;
}

for (int i = 0; i < s.length(); i++) {
String ss;
if (i > s.length() - num) {//不重复子串小于num且在s末尾
ss = s.substring(i);
} else {
ss = s.substring(i, i + num);
}
int t = len(ss);
res = t > res ? t : res;
}
return res;
}

public int len(String s) {//从左开始判断最长不重复子串长度
int[] cs = new int[256];
int lens = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (cs[c] == 1) return lens;
else cs[c] = 1;
lens++;
}
return lens;
}
}

文章作者: Amos Liu
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Amos Liu !
 上一篇
Java自动装箱/拆箱 Java自动装箱/拆箱
Java自动装箱/拆箱什么是装箱/拆箱​ 在Java中一共有四类八种基本数据类型,在JDK1.5中,给这四类八种基本数据类型加入了包装类,对应如下: 基本类型 包装类型 byte Byte short Short
2017-04-02
下一篇 
Java基本类型 Java基本类型
Java基本类型​ Java中的变量分为基本类型和引用类型。基本类型是一些特别小的、简单的变量,对于这种变量,直接存储值并放在堆栈中会更高效;引用类型是和Java对象所关联的一个操纵对象的标识符,可以通过new操作符使引用和相应的对象
2017-03-27
  目录