解题思路:
题目也水,数据也水
注意事项:
注意循环终止条件,不要死循环了
参考代码:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <vector> #include <string> #include <algorithm> #include <stdio.h> #define N 10000 using namespace std; string necklace; vector<int> ansSet; int scanLeft(int startPos, int len) { int totalLen = 0; int i = (startPos + len - 1) % len; int origI = i; bool first = true; bool setColor = false; char strColor = 0; while ((i != origI && !first) || first) { if (first) first = false; //颜色已决 if (setColor) { if (necklace[i] == 'w' || necklace[i] == strColor) totalLen += 1; else break; } else { if (necklace[i] != 'w') { strColor = necklace[i]; setColor = true; } totalLen += 1; } i = (i + len - 1) % len; } return totalLen; } int scanRight(int startPos, int len) { int totalLen = 0; int i = (startPos + len) % len; bool first = true; bool setColor = false; char strColor = 0; while ((i != startPos && !first) || first) { if (first) first = false; //颜色已决 if (setColor) { if (necklace[i] == 'w' || necklace[i] == strColor) totalLen += 1; else break; } else { if (necklace[i] != 'w') { strColor = necklace[i]; setColor = true; } totalLen += 1; } i = (i + len + 1) % len; } return totalLen; } int solve() { int len = necklace.length(); int leftLen = 0, rightLen = 0; for (int i = 0; i < len; i++) { leftLen = scanLeft(i, len); rightLen = scanRight(i, len); ansSet.push_back(leftLen + rightLen); } return *max_element(ansSet.begin(), ansSet.end()); } int main(int argc, char** argv) { cin >> necklace; cout << solve() << endl; return 0; }
附赠官方标答:
#include <stdio.h> #include <string.h> #include <ctype.h> #include <string> #include <map> #include <set> #include <vector> using namespace std; int len; int getnum(string& s) { int res = 0, i=0; while (s[i] == 'w') { i++; if (i==len) return i; } res = i+1; char t = s[i]; ++i; while ((s[i]==t ||s[i]=='w')&& s[i] != 0) { ++i; res++; } if (res == len) return res; i = len-1; while (s[i] == 'w') { res++; --i; } res++; t = s[i]; --i; while (i>=0 && (s[i]==t || s[i]=='w')) { res++; --i; } if (res > len) res = len; return res; } int main() { char str[110]; scanf("%s", str); len = strlen(str); string s; int sum = 0, t; for (int i=0; i<len; ++i) { s = &str[i]; for (int j=0; j<i; ++j) { s += str[j]; } t = getnum(s); if (t > sum) { sum = t; } } printf("%d\n", sum); return 0; }
0.0分
0 人评分