力扣20 ,有效的括号 ,栈
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
cin >> s;
stack<char> z;
int i=0;
while(s[i]!='\0'){
if(s[i] == '('||s[i]=='['||s[i]=='{'){
z.push(s[i]);
}else{
if(z.size()==0){
printf("false");
return 0;
}
if(s[i]==')'&&z.top()=='(')z.pop();
else if(s[i]==']'&&z.top()=='[')z.pop();
else if(s[i]=='}'&&z.top()=='{')z.pop();
else {
printf("false");
return 0;
}
}
i++;
}
if(z.size()==0){
printf("true");
}else{
printf("false");
}
return 0;
}
力扣206,链表反转(面试考)
定义一个永远指向第一个元素的dummy指针,让head指针固定不变,将head.next接在前面实现反转。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *dummy = head;
while(head!=NULL&&head->next!=NULL){
ListNode *cdummy = dummy;
ListNode *hnext = head->next;
dummy = hnext;
head->next = hnext->next;
hnext->next = cdummy;
}
return dummy;
}
};
力扣389,找不同,s串中出现就减,t串中出现就加。哈希表
理解一下s[i]-‘a’, char z=i+‘a’;
class Solution {
public