代碼題(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; }
相關文章
相關標籤/搜索