思路:结合上一篇博客中的 有重复数的全排列 生成所有的可能,再添加一个check()判断字符串是否合法即可!
class Solution {
public:
vector<int> vis;
void dfs(set<string>& res, string& s, int idx, string& tmp){
if(idx==s.size()){
res.insert(tmp);
return;
}
for(int i = 0; i < s.size(); i ++){
if(vis[i]||(i&&s[i]==s[i-1]&&!vis[i-1])) continue;
vis[i] = 1;
tmp += s[i];
dfs(res, s, idx+1, tmp);
vis[i] = 0;
tmp.erase(tmp.size()-1, 1);
}
}
bool check(string s){
stack<char> stk;
for(auto x:s){
if(stk.empty()||x=='(') stk.push(x);
else{
if(stk.top()=='('){
stk.pop();
}
else stk.push(x);
}
}
return stk.empty();
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
string s, tmp;
for(int i = 1; i <= n; i ++) s += "()";
sort(s.begin(), s.end());
set<string> res;
vis.resize(s.size());
dfs(res, s, 0, tmp);
for(auto x:res){
if(check(x)) ans.push_back(x);
}
return ans;
}
};
class Solution {
public:
int longestPalindrome(string s) {
if(s.size()==1) return 1;
sort(s.begin(), s.end());
// cout << s << endl;
int ans = 0, flag = 0, cnt = 1;
for(int i = 1; i < s.size(); i ++){
if(s[i]==s[i-1]) cnt ++;
else{
// cout << "i: " << i << " cnt: " << cnt << endl;
if(cnt%2){
flag = 1;
ans += cnt-1;
}
else ans += cnt;
cnt = 1;
}
if(i==s.size()-1){
ans += (cnt%2?(flag?cnt-1:cnt):cnt);
}
}
return ans+flag;
}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL||head->next==NULL) return false;
set<ListNode*> st;
while(head){
if(st.count(head)) return true;
st.insert(head);
head = head->next;
}
return false;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr||head->next==nullptr) return head;
ListNode* ans = reverseList(head->next);
head->next->next = head; //将head->next的next值置为head
head->next = nullptr; //head指向空
return ans;
}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummy = new ListNode(0); //开一个动态的链表
dummy->next = head; //表头指向head
ListNode* tmp = dummy;
while(tmp->next&&tmp->next->next){
ListNode* a = tmp->next;
ListNode* b = tmp->next->next; //tmp->a->b->c
tmp->next = b; //tmp->b, a->b
a->next = b->next; //tmp->b, a->c
b->next = a; //tmp->b->a->c
tmp = a;
}
return dummy->next;
}
};