题解 | #字符串中找出连续最长的数字串#
字符串中找出连续最长的数字串
https://www.nowcoder.com/practice/bd891093881d4ddf9e56e7cc8416562d
#include <iostream>
#include <string>
using namespace std;
bool IsContinuousDigit(string& str, int begin, int end){
for(begin; begin < end; ++begin){
if(!isdigit(str[begin]))
return false;
}
return true;
}
bool IsContinuousAlpha(string& str, int begin, int end){
for(begin; begin < end; ++begin){
if(!isalpha(str[begin]))
return false;
}
return true;
}
int main()
{
string str;
cin >> str;
auto it = str.begin();
int maxCount = 0, count = 0;
while(it != str.end()){
count = 0; // 重置count
if(isalpha(*it)){ // 字母
while(it != str.end() && isalpha(*it)){ // 一直是字母
++it;
++count;
}
maxCount = max(maxCount, count);
}
else{
while(it != str.end() && isdigit(*it)){ // 一直是数字
++it;
++count;
}
maxCount = max(maxCount, count);
}
}
string ret;
// 寻找maxCount个数据的子串
for(size_t i = 0; i < str.size(); i++){
if(IsContinuousDigit(str, i, i+maxCount) || IsContinuousDigit(str, i, i+maxCount))
ret += str.substr(i, maxCount);
}
cout << ret << endl;
}
由于我一开始看错题目了,把字符串看成数字串。因此多了很多多余操作。
如果只是数字串的话。可以考虑用一个额外的空间tmp来存储全是数字的串,然后当走到不是数字时,与ret比较哪个大,tmp大就把tmp的内容赋值给ret,如果ret大,就清空tmp
继续遍历。
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str, tmp, ret;
cin >> str;
for(size_t i = 0; i < str.size(); ++i)
{
if(str[i] >= '0' && str[i] <= '9'){
tmp += str[i];
}
else{ // 非数字时比较size大小
if(tmp.size() > ret.size())
ret = tmp;
else
tmp.clear();
}
}
// i走到\0的时候,也有可能最后的数字串是最大的,
// 但此时因为已经跳出for循环了,因此需要再比较一次
if(tmp.size() > ret.size())
ret = tmp;
else
tmp.clear();
cout << ret << endl;
return 0;
}
海康威视公司福利 1216人发布