【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 ...
随机推荐
- [HAOI2015]按位或
题目 好神的题啊 我们发现我们求这个东西如果常规\(dp\)的话可以建出一张拓扑图来,但是边的级别高达\(3^n\),转移的时候还要解方程显然不能通过本题 我们考虑神仙的\(min-max\)容斥 设 ...
- Day5 类和对象
面向对象编程OOP 类:相似对象的集合. 对象 对象:实体.一切可以被描述的事物. 属性:特征. 方法:动作,行为. 类和对象的区别 [1]类时抽象的,对象是具体的. [2]类是一个模板,创建出来的对 ...
- React-Native 之 index.android.bundle
问题: index.android.bundle 这个bug 我相信很少同学会遇到,然而就是这个问题,困扰了我跟我的同事多天, 各种方法处理: 进入 android 目录 ./gradlew c ...
- tuple元组详解
这次要讲的内容是:c++11中的tuple(元组).tuple看似简单,其实它是简约而不简单,可以说它是c++11中一个既简单又复杂的东东,关于它简单的一面是它很容易使用,复杂的一面是它内部隐藏了太多 ...
- Redis——总结
启动 redis 客户端,打开终端并输入命令 redis-cli.该命令会连接本地的 redis 服务. $redis-cli redis 127.0.0.1:6379> redis 127.0 ...
- MySQL数据库启停
坑1:net start mysql 提示:服务名无效 1.win+R打开运行窗口,输入services.msc 2.在其中查看mysql的服务名,我的是MySQL55 3.以管理员身份打开cmd,输 ...
- 1360: Good Serial Inc.(不知道是什么类型的题)
1360: Good Serial Inc. Submit Page Summary Time Limit: 1 Sec Memory Limit: 128 Mb Subm ...
- HDU变形课
变形课 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)Total Submis ...
- jQuery----(类似抽奖转盘)高亮显示
效果如图: 原图 鼠标进入后开始变化图 实现需 ...
- Linux --- vim 安装、支持python3的配置、插件自动补全YCM的安装配置及全过程错误总结
1.git(用来下载vim和相关插件) sudo apt-get install git 2,cmake(用来编译clang-llvm) sudo apt-get install build-esse ...