70,3超时,求优化

P1308 [NOIP2011 普及组] 统计单词数

```cpp #include<bits/stdc++.h> using namespace std; string s, word; int ans,ans1; bool maybe; int main() { getline(cin, word); getline(cin, s); int len = s.size(), len2 = word.size(); for(int i=0;i<= len - len2; i++) { int j; for (j = 0; j < len - 1; ++j) { if (toupper(s[i + j]) != toupper(word[j])) break; if (i && s[i - 1] != ' ') break; } if (j == len2 && (s[i + j] == ' ' || j + i == len)) { ++ans; if (ans == 1) ans1 = i; } } if(ans==0) { cout<<-1; } else { cout<<ans<<" "<<ans1; } return 0; } ```
by FurippuWRY @ 2024-01-29 11:05:09


AC ```c #include<bits/stdc++.h> using namespace std; int first=-1; int main(){ string str1,str2,str3=""; char ch; int flag=0,num=0; cin>>str1; transform(str1.begin(),str1.end(),str1.begin(),::tolower); ch=getchar(); getline(cin,str2); int len=str2.size(); for(int i=0;i<len;i++) { if(str2[i]==' ') { if(flag==0) continue; if(str1==str3) { if(first==-1) first=i-str3.size(); num++; } str3.clear(); } else{ flag=1; if(str2[i]>='A'&&str2[i]<='Z') str2[i]+=32; str3+=str2[i]; } } if(str1==str3) { if(first==-1) first=len-str3.size(); num++; } if(first==-1) cout<<"-1"; else cout<<num<<" "<<first; return 0; } ```
by timmyliao @ 2024-01-29 11:11:56


```cpp #include<bits/stdc++.h> using namespace std; int main(){ string s, word; int count=0, start, pos; getline(cin, word); getline(cin, s); word =" "+word+" "; s=" "+s+" "; for(int i=0; i<word.size(); i++){ if(word[i]>='A'&&word[i]<='Z'){ word[i]+=32; } } for (int i=0; i<s.size(); i++){ if (s[i]>='A'&&s[i]<='Z'){ s[i]+=32; } } if(s.find(word)!=-1){ pos=s.find(word); start=s.find(word); count++; } else{ cout<<-1; return 0; } do{ s=s.substr(pos+word.size()-1); if(s.find(word)!=-1){ pos=s.find(word); count++; } else{ break; } }while(1==1); cout << count << " " << start; return 0; } ``````
by infinity_ZM @ 2024-01-29 11:14:46


|