目录
一、题目
二、解答
(一)问题一:在记录完一组连续字符串后,没有注意判别紧随其后的非数字字符
(二)问题二:越界访问
(三)正确
一、题目
字符串中找出连续最长的数字串_牛客题霸_牛客网
二、解答
(一)问题一:在记录完一组连续字符串后,没有注意判别紧随其后的非数字字符
#include <iostream>
#include <cstdbool>
#include <string>
using namespace std;#include <iostream>
#include <cstdbool>
#include <string>
using namespace std;int main() {string s;cin >> s;int prev = 0, next = 0;string s2;bool isfirst = false;while (next < s.length()) {if (s[next] <= '9' && s[next] >= '0') {if (isfirst == false) {prev = next;isfirst = true;}++next;} else {isfirst = false;if (next - prev > s2.length()) {s2 = s.substr(prev, next - prev);}++next;}}if (next - prev > s2.length()) {s2 = s.substr(prev, next - prev);}cout << s2;return 0;}
(二)问题二:越界访问
#include <iostream>
#include <cstdbool>
#include <string>
using namespace std;int main() {string s;cin >> s;int prev = 0, next = 0;string s2;bool isfirst = false;while (next < s.length()) {if (s[next] <= '9' && s[next] >= '0'){if (isfirst == false){prev = next;isfirst = true;}++next;}else{isfirst = false;if (s[next - 1] <= '9' && s[next - 1] >= '0'){if (next - prev > s2.length()){s2 = s.substr(prev, next - prev);}}++next;}}if (s[next - 1] <= '9' && s[next - 1] >= '0'){if (next - prev > s2.length()) //注意最后一个数字串{s2 = s.substr(prev, next - prev);}}cout << s2;return 0;}
(三)正确
#include <iostream>
#include <cstdbool>
#include <string>
using namespace std;int main() {string s;cin >> s;int prev = 0, next = 0;string s2;bool isfirst = false;//判断prev是不是第一次出现while (next < s.length()) {if (s[next] <= '9' && s[next] >= '0'){if (isfirst == false){prev = next;isfirst = true;}++next;}else{isfirst = false;if (s[prev] <= '9' && s[prev] >= '0' && s[next - 1] <= '9' && s[next - 1] >= '0'){if (next - prev > s2.length()){s2 = s.substr(prev, next - prev);}}++next;}}if (s[next - 1] <= '9' && s[next - 1] >= '0')//注意跳出循环后的最后一个数字串{if (next - prev > s2.length()) {s2 = s.substr(prev, next - prev);}}cout << s2;return 0;}