第一次发现string 的erase函数是o(1)的复杂度,直接模拟
#include<bits/stdc++.h> using namespace std; int book[100010]; int main() { string s; cin>>s; int len=s.size()-1; int cnt=0; for(int i=0;s[i];i++) { //printf("**%d ",i); if(s[i]==s[i+1]) { //printf("%d ",i); cnt++; s.erase(s.begin()+i); //cout<<s<<endl; s.erase(s.begin()+i); if(i==0) i--; else i-=2; //cout<<s<<endl; //printf("%d ",cnt); } } if(cnt%2==1) printf("Yes "); else printf("No "); }
还可以用栈,如果发现入栈的字符和栈顶相同,cnt++,并弹出栈顶
#include<bits/stdc++.h> #define int long long #define MAX(a,b,c) max(a,max(b,c)) #define MIN(a,b,c) min(a,min(b,c)) #define pb push_back #define fi first #define se second typedef long long ll; typedef long long LL; typedef unsigned long long ull; typedef unsigned long long uLL; using namespace std; const int maxn=1e6+10; const int mod=1e9+10; int32_t main() { string ss; cin>>ss; int ans=0; stack<char> st; for(int i=0;i<ss.size();i++) { if(st.size()==0) st.push(ss[i]); else { if(ss[i]==st.top()) { ans++; st.pop(); } else { st.push(ss[i]); } } } if(ans%2==0) cout<<"No"<<endl; else cout<<"Yes"<<endl; }