删除排序链表中的重复元素(链表)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* deleteDuplicates(ListNode* head) {
// write code here
if(!head) return NULL;
auto cur = head;
while(cur->next){
if(cur->val == cur->next->val) cur->next = cur->next->next;
else cur = cur->next;
}
return head;
}
};
最长的括号子串(括号序列的性质,栈)
解法一:利用括号序列的性质 —> 前缀和 >= 0 && 总和 == 0
class Solution {
public:
/**
*
* @param s string字符串
* @return int整型
*/
int work(string &s) // 括号序列的性质 ---> 前缀和 >= 0 && 总和 == 0
{
int res = 0;
int cnt = 0;
for(int i = 0, start = 0;i < s.size();i ++ )
{
if(s[i] == '(') cnt ++;
else
{
cnt -- ;
if(cnt < 0) start = i + 1,cnt = 0;
if(cnt == 0) res = max(res,i - start + 1);
}
}
return res;
}
int longestValidParentheses(string s) {
// write code here
int res = work(s);
reverse(s.begin(),s.end());
for(auto &c : s) c ^= 1; // 正反做一遍
res = max(res,work(s));
return res;
}
};
解法2:栈
class Solution {
public:
/**
*
* @param s string字符串
* @return int整型
*/
/*
(栈) O(n)
1. 用栈维护当前待匹配的左括号的位置。同时用 start 记录一个新的可能合法的子串的起始位置。初始设为 0。
2. 遇到左括号,当前位置进栈。
3. 遇到右括号,如果当前栈不空,则当前栈顶出栈。出栈后,如果栈为空,则更新答案 i - start + 1;否则更新答案 i - st.top()。
4. 遇到右括号且当前栈为空,则当前的 start 开始的子串不再可能为合法子串了,下一个合法子串的起始位置是 i + 1,更新 start = i + 1
时间复杂度
每个位置遍历一次,最多进栈一次,故时间复杂度为 O(n)O(n)。
*/
int longestValidParentheses(string s) {
// write code here
int n =s.size();
stack<int> st;
int start = 0,ans = 0;
for(int i=0;i<n;i++)
{
if(s[i] == '(') st.push(i);
else
{
if(st.size())
{
st.pop();
if(st.empty()) ans = max(ans,i - start + 1);
else ans = max(ans,i - st.top());
}
else
{
start = i + 1;
}
}
}
return ans;
}
};
序列化二叉树(递归)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res;
dfs1(root,res);
return res;
}
void dfs1(TreeNode*root,string &s)
{
if(!root)
{
s += "#!";
return;
}
s += to_string(root->val) + '!';
dfs1(root->left,s);
dfs1(root->right,s);
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int u = 0;
return dfs2(data,u);
}
TreeNode* dfs2(string &data,int &u)
{
if(data[u] == '#')
{
u += 2;
return NULL;
}
int sign = 1;
if(data[u] == '-')
{
sign = -1;
u ++ ;
}
int t = 0;
while(data[u] != '!')
{
t = t * 10 + data[u] - '0';
u ++ ;
}
u ++ ;
t = t *sign;
auto root = new TreeNode(t);
root->left = dfs2(data,u);
root->right = dfs2(data,u);
return root;
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));