- leetcode题解备份,括号内为题号
- add two numbers(2)
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null && l2 != null) {
return l2;
} else if (l1 != null && l2 == null) {
return l1;
} else if (l1 == null && l2 == null) {
return null;
}
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
int carry = 0;
while (l1 != null || l2 != null) {
int d1 = l1 == null? 0 : l1.val;
int d2 = l2 == null? 0 : l2.val;
int sum = d1 + d2 + carry;
carry = sum >= 10? 1 : 0;
cur.next = new ListNode(sum % 10);
cur = cur.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
if (carry == 1) cur.next = new ListNode(1);
return dummy.next;
}
}
// 错误的解法!!!
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
int carry = 0;
int sum = 0;
int num1 = 0;
int num2 = 0;
// 记录链表头部
ListNode head = new ListNode(-1);
ListNode cur = head.next; // 此处cur指向null!!!不能使head.next指向预期的节点。
// 这里也体现了java和C的区别,java无显式指针
// 同时遍历两个list
while (l1 != null || l2 != null) {
num1 = l1 == null? 0: l1.val;
num2 = l2 == null? 0: l2.val;
sum = num1 + num2 + carry;
carry = sum / 10;
cur = new ListNode(sum % 10);
cur = cur.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
if (carry != 0) cur = new ListNode(carry);
return head.next;
}
}
- Longest Substring Without Repeating Characters(3)
查找最长子串长度
class Solution {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int[] m = new int[256];
Arrays.fill(m, -1);
int res = 0, left = -1;
for (int i = 0; i < s.length(); ++i) {
left = Math.max(left, m[s.charAt(i)]);
m[s.charAt(i)] = i;
res = Math.max(res, i - left);
}
return res;
}
// method two
/*
if (s == null || s.length() == 0) {
return 0;
}
int maxLen = 0;
int curLen = 0;
Map<Character, Integer> map = new HashMap<Character, Integer>();
int i = 0;
while (i < s.length()) {
char ch = s.charAt(i);
if (!map.containsKey(ch)) {
map.put(ch, i);
curLen++;
i++;
} else {
i = map.get(ch) + 1;
maxLen = maxLen >= curLen? maxLen : curLen;
curLen = 0;
map.clear();
}
}
if (curLen != 0) {
maxLen = maxLen >= curLen? maxLen: curLen;
}
return maxLen;
*/
/*
// 滑动窗口
if (s == null || s.length() == 0) {
return 0;
}
int start = -1;
int res = 0;
int tmp;
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (!map.containsKey(ch)) {
} else {
tmp = map.get(ch);
if (start < tmp) {
start = tmp; // start位置的更新逻辑
}
}
map.put(ch, i);
if (i - start > res) {
res = i - start;
}
}
return res;
*/
}