(一)剑指Offer48. 最长不含重复字符的子字符串
基本思路:
1.这道题没有什么巧妙的算法,维护一个窗口,保存窗口的最左端位置,并将窗口内的字符以<键:字符,值:位置>存入HashMap中。当有重复字符出现时,就更新HashMap中该键对应的坐标,并将长度与最大长度进行对比更新。
class Solution {
public int lengthOfLongestSubstring(String s) {
//设置一个hashmap,存储每个字符出现的最新位置
//设置一个left变量,存储未重复字符串的最左侧
//设置一个数组,存储每个字符上一次出现的位置,两次距离最小大的即为最长子串
//考虑特殊情况:到结尾的字符串恰好是最长的一个
char[] chars = s.toCharArray();
//划定当前窗口的坐标为(start,i],左开右闭,所以start的初始值为-1,而非0。
int left = -1;
int maxLen = 0;
int j = 0;
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < chars.length; i++) {
if (map.containsKey(chars[i])) {
//如果hash表里有相同的key,更新left
left = Math.max(left, map.get(chars[i]));
}
//更新hash表
map.put(chars[i], i);
maxLen = Math.max(maxLen, i - left);
}
return maxLen;
}
}
(二)剑指Offer50. 第一个只出现一次的字符
class Solution {
public char firstUniqChar(String s) {
HashMap<Character, Boolean> dic = new HashMap<>();
char[] sc = s.toCharArray();
for(char c : sc)
dic.put(c, !dic.containsKey(c));
for(char c : sc)
if(dic.get(c)) return c;
return ' ';
}
}
(三)剑指 Offer 35. 复杂链表的复制
基本思路:
这道题根据next可以依次新建新的链表结点,这个是比较简单的,难的是如何创建random指针。可以创建一个HashMap,值和键分别为新的结点和对应的旧结点,这样我们就可以简单地根据原来指向的旧结点找到新结点了。
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
if(head == null) return null;
Node cur = head;
Map<Node, Node> map = new HashMap<>();
// 3. 复制各节点,并建立 “旧节点 -> 新节点” 的 Map 映射
while(cur != null) {
map.put(cur, new Node(cur.val));
cur = cur.next;
}
cur = head;//把所有的新节点都放入了map
// 4. 构建新链表的 next 和 random 指向
while(cur != null) {
map.get(cur).next = map.get(cur.next);
map.get(cur).random = map.get(cur.random);
cur = cur.next;
}
// 5. 返回新链表的头节点
return map.get(head);
}
}