概述
20. Valid Parentheses
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
1.Open brackets must be closed by the same type of brackets.
2.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
Solution in C++:
关键点:如何表示括号及其匹配问题
bool isValid(string s) {
map<char,int> myMap;
myMap['('] = 1;
myMap[')'] = 2;
myMap['['] = 4;
myMap[']'] = 5;
myMap['{'] = 7;
myMap['}'] = 8;
vector<char> vec;
size_t i = 0;
for (auto c : s)
{
if(myMap[c] == 0)
return false;
if (!vec.empty()){
if (myMap[vec.back()] != (myMap[c]-1))
vec.push_back(c);
else
vec.pop_back();
} else{
vec.push_back(c);
}
}
if (vec.empty())
return true;
else
return false;
}
21. Merge Two Sorted Lists
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
Solution in C++:
方法一:没有头结点
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* merge = nullptr;
ListNode* ret = nullptr;
if (l1 == nullptr) return l2;
if (l2 == nullptr) return l1;
if (l1->val < l2->val){
merge = l1;
l1 = l1->next;
} else{
merge = l2;
l2 = l2->next;
}
ret = merge;
while(l1 && l2){
if (l1->val < l2->val){
merge->next = l1;
l1 = l1->next;
} else{
merge->next = l2;
l2 = l2->next;
}
merge = merge->next;
}
if (l1){
merge->next = l1;
} else{
merge->next = l2;
}
return ret;
}
方法二:有头结点
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *head= new ListNode(-1), *cur = head;
while (l1 && l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 ? l1 : l2;
return head->next;
}
错误写法(只写函数体内的代码):
ListNode* merge = nullptr;
ListNode* ret = nullptr;
bool flag = true;
while(l1 && l2){
if (l1->val <= l2->val){
merge = l1;
l1 = l1->next;
} else{
merge = l2;
l2 = l2->next;
}
if (flag){
ret = merge;
flag = false;
}
merge = merge->next;
}
if (l1){
merge = l1;
} else{
merge = l2;
}
return ret;
错误分析:此处写法,merge的作用是想将l1和l2链表的结点链接起来,但是实际作用merge指针只是指向了不同的结点,而并未改变结点next指针域的指向。
小结
1.练习了C++中map和vector的使用
2.对链表的知识进行了复习,但是发现掌握的并不好,还有对指针的理解也存在一定的问题。之后会对链表知识专门进行整理,并且在日后的刷题过程中也需要对链表的使用进行总结。
3.链表中结点之间的链接改变是通过next指针域的改变而改变的。
最后
以上就是天真咖啡为你收集整理的[日常刷题]leetcode第四天的全部内容,希望文章能够帮你解决[日常刷题]leetcode第四天所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复