【LeetCode算法题库】Day7:Remove Nth Node From End of List & Valid Parentheses & Merge Two Lists
【Q19】
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
def removeNthFromEnd(self, head: 'ListNode', n: 'int') -> 'ListNode': cur = head
length = 0
while cur!=None:
cur = cur.next
length += 1 if length==0:
return head
else:
idx = 0
if length-n==0:
return head.next
else:
cur = head
while idx<length-n-1:
cur = cur.next
idx += 1
cur.next = cur.next.next
return head
【Q20】
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
解法:用堆栈。遍历字符串数组,把左括号全部压栈,遇到右括号时,判断与栈顶的左括号是否为一对,若是,则令栈顶的左括号出栈,判断遍历完毕的栈是否为空。若是,则返回True,否则返回False。
详解(直接看最后的solution):https://leetcode.com/problems/valid-parentheses/solution/
class Solution:
def isValid(self, s: 'str') -> 'bool': charmap = {')':'(',']':'[','}':'{'}
if s==None:
return True if len(s)%2!=0:
return False stack = []
for i in range(len(s)):
if i==0:
stack.append(s[i])
elif s[i] in charmap:
c = stack.pop()
if c!=charmap.get(s[i]):
return False
else:
stack.append(s[i])
return not stack
【Q21】
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4 注意保存链表头!
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
def mergeTwoLists(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode': head = l = ListNode(None) while l1 and l2:
if l1.val<l2.val:
l.next = l1
l1 = l1.next
else:
l.next = l2
l2 = l2.next
l = l.next
if not l1:
l.next = l2
else:
l.next = l1
return head.next
【LeetCode算法题库】Day7:Remove Nth Node From End of List & Valid Parentheses & Merge Two Lists的更多相关文章
- 【leetcode刷题笔记】Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head. For example, Give ...
- LeetCode解题报告—— 4Sum & Remove Nth Node From End of List & Generate Parentheses
1. 4Sum Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + ...
- LeetCode第[19]题(Java):Remove Nth Node From End of List(删除链表的倒数第N个节点)
题目:删除链表的倒数第N个节点 难度:Medium 题目内容: Given a linked list, remove the n-th node from the end of list and r ...
- LeetCode OJ 292.Nim Gam19. Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head. For example, Give ...
- 【Leetcode】【Easy】Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head. For example, Give ...
- 【LeetCode算法题库】Day4:Regular Expression Matching & Container With Most Water & Integer to Roman
[Q10] Given an input string (s) and a pattern (p), implement regular expression matching with suppor ...
- 【LeetCode算法题库】Day1:TwoSums & Add Two Numbers & Longest Substring Without Repeating Characters
[Q1] Given an array of integers, return indices of the two numbers such that they add up to a specif ...
- 【LeetCode算法题库】Day3:Reverse Integer & String to Integer (atoi) & Palindrome Number
[Q7] 把数倒过来 Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Outpu ...
- 【LeetCode算法题库】Day2:Median of Two Sorted Arrays & Longest Palindromic Substring & ZigZag Conversion
[Q4] There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of th ...
随机推荐
- Java基础知识强化之集合框架笔记80:HashMap的线程不安全性的体现
1. HashMap 的线程不安全性的体现: 主要是下面两方面: (1)多线程环境下,多个线程同时resize()时候,容易产生死锁现象.即:resize死循环 (2)如果在使用迭代器的过程中有其他线 ...
- Jinja2 简明使用手册
@Jinja2 简明使用手册(转载) 介绍 Jinja是基于python的模板引擎,功能比较类似于于PHP的smarty,J2ee的Freemarker和velocity. 运行需求 Jinja2需要 ...
- 【[BJOI2017]魔法咒语】
矩阵乘法+\(AC\)自动机 是道很不错的题了 首先是前六十分,就是一个\(AC\)自动机上的套路\(dp\),设\(dp[i][j]\)表示匹配出的长度为\(i\)在自动机上位置为\(j\)的方案数 ...
- 利用MATLAB软件对数码相机进行检校
分享资料:https://pan.baidu.com/s/1FQb-ttLJNJKlMzu-0RjBsw.内部包含张正友的经典论文等文献,官网的checkerboardPattern等.
- 分别编写两个类Point2D,Point3D来表示二维空间和三维空间的点,使之满足下列要求:
(1) Point2D有两个整型成员变量x, y (分别为二维空间的X,Y方向坐标),Point2D的构造方法要实现对其成员变量x, y的初始化. (2)Point2D有一个void型成员方法offs ...
- P1070 道路游戏
题目描述 小新正在玩一个简单的电脑游戏. 游戏中有一条环形马路,马路上有 n 个机器人工厂,两个相邻机器人工厂之间由一小段马路连接.小新以某个机器人工厂为起点,按顺时针顺序依次将这 n 个机器人工厂编 ...
- HDU 1950(LIS)
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1950 Bridging signals Time Limit: 5000/1000 MS (Java ...
- linux文件系统初始化过程(5)---加载initrd(下)
一.目的 linux把文件分为常规文件.目录文件.软链接文件.硬链接文件.特殊文件(设备文件.管道文件.socket文件等)几种类型,分别对应不同的新建函数sys_open().sys_mkdir() ...
- 基于Babylon.js编写简单的骨骼动画生成器
使用骨骼动画技术可以将网格的顶点分配给若干骨头,通过给骨头设定关键帧和父子关系,可以赋予网格高度动态并具有传递性的变形 效果.这里结合之前的相关研究在网页端使用JavaScript实现了一个简单的骨骼 ...
- Hive--可执行SQL的Hadoop数据仓库管理工具
Hive是一个基于HDFS的数据仓库软件,可理解为数据库管理工具:Hive的功能主要有: 1. 支持使用SQL对分布式存储的大型数据集进行读.写.管理,将SQL转化成MapReduce任务执行: 2. ...