剑指Offer学习
PinkyZ
这个作者很懒,什么都没留下…
展开
-
剑指 Offer 58 - II. 左旋转字符串
切片方法 String中的substring()函数是左闭右开的。 class Solution { public String reverseLeftWords(String s, int n) { String l = s.substring(0,n); String r = s.substring(n,s.length()); String res = r+l; return res; } } ...原创 2021-08-30 13:53:59 · 34 阅读 · 0 评论 -
剑指 Offer 05. 替换空格
String类型在java中是不可变。注意使用StringBuilder,方便添加,空间复杂度 O(n)。 class Solution { public String replaceSpace(String s) { int size = s.length(); StringBuilder res = new StringBuilder(); for (int i =0;i<size;i++){ if(s.charA原创 2021-08-30 13:42:40 · 41 阅读 · 0 评论 -
剑指 Offer 35. 复杂链表的复制
本题重点在于怎么个复制法(包含random指针)。 两种方法:1、哈希表 2、拼接与拆分 1、哈希表 特点在于将节点保存,取节点及链接时方便。 class Solution { public Node copyRandomList(Node head) { if(head == null) return null; Node cur = head; Map<Node, Node> ...原创 2021-08-27 16:56:37 · 35 阅读 · 0 评论 -
剑指 Offer 24. 反转链表
注意改题没有头节点,要好好处理。 ListNode p = new ListNode(-1); 给p一个头节点,方便操作,后续返回时返回p.next即可。 class Solution { public ListNode reverseList(ListNode head) { ListNode p = new ListNode(-1); ListNode q = head; while (head!=null){ q原创 2021-08-27 15:34:20 · 43 阅读 · 0 评论 -
剑指 Offer 06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 重点在于用数组返回,立刻想到 栈 的特点 class Solution { public int[] reversePrint(ListNode head) { Stack<Integer> stk = new Stack<>(); while(head!=null){ stk.push(head.val); head=h原创 2021-08-27 14:37:52 · 45 阅读 · 0 评论 -
剑指 Offer 30. 包含min函数的栈
要点:存储最小值--双栈存储,最小值栈只存入不比头元素大的。出栈时进行比较,存在相同的元素时,最小值栈才出栈。 public class MinStack { /** initialize your data structure here. */ Stack<Integer> stk; Stack<Integer> Min; public MinStack() { stk = new Stack<Integer>();原创 2021-08-23 10:38:29 · 34 阅读 · 0 评论 -
剑指 Offer 09. 用两个栈实现队列
改进:之前没有优化,仅是每次要delete时整两次循环返还给stk1。 去除一个循环----即stk1用来存数据,stk2输出数据。仅需在stk2中无数据时才进行一次倒换(循环)。 class CQueue { Stack<Integer> stk1; Stack<Integer> stk2; public CQueue() { stk1 = new Stack<Integer>(); ...原创 2021-08-23 10:02:39 · 48 阅读 · 0 评论