代码题(58)— 字符串中找出连续最长数字串

0、在线测试问题:ios

  一、本地经过,但在线测试没有经过率的问题:面试

  解决方法:测试

  (1)将程序包在下面代码里面试一试。spa

while (cin >> str) { }

  (2)将程序别包含在上面代码中再试一试。code

  二、考虑一下边界条件问题blog

 

一、题目描述一:读入一个字符串str,输出字符串str中的连续最长的数字串ci

    • 输入描述: 
      个测试输入包含1个测试用例,一个字符串str,长度不超过255。字符串

    • 输出描述: 
      在一行内输出str中里连续最长的数字串。string

    • 输入 
      abcd12345ed125ss123456789it

    • 输出 
      123456789

   思路:循环判断每个位置处的数字子串长度,保留最长子串。

#include<iostream> #include<algorithm> #include<stdio.h> #include <vector> #include<string> #include<sstream> #include<map> #include<set> #include <functional> // std::greater
using namespace std; int main() { string str; cin >> str; int maxlen = 0; string res; for (int i = 0; i < str.size(); ++i) { if (str[i] >= '0'&& str[i] <= '9') { int temp = i; while (str[i] >= '0'&& str[i] <= '9') i++; if (maxlen <= i - temp) { maxlen = i - temp; res = str.substr(temp, maxlen); } } } cout << res << endl; system("pause"); return 0; }

二、读入一个字符串str,输出字符串str中的连续最长的数字串

输入描述: 个测试输入包含1个测试用例,一个字符串str,长度不超过255。

输出描述:在一行内输出str中里连续最长的数字串。

示例1:abcd12345ed125ss123456789
输出:123456789
#include<iostream> #include<algorithm> #include<stdio.h> #include <vector> #include<string> #include<sstream> #include<map> #include<set> #include <functional> // std::greater
using namespace std; int main() { string str; while (cin >> str) { int maxlen = 0; string res; for (int i = 0; i < str.size(); ++i) { if (str[i] >= '0'&& str[i] <= '9') { int temp = i; while (str[i] >= '0'&& str[i] <= '9') i++; if (maxlen < i - temp) { maxlen = i - temp; res = str.substr(temp, maxlen); } else if (maxlen == i - temp) res += str.substr(temp, maxlen); } } cout << res << ',' << maxlen << endl; } system("pause"); return 0; }
相关文章
相关标签/搜索