在C++中查詢字串中最長數字長度
在這個問題中,我們得到一個僅包含字元和字母的字串str。我們的任務是查詢字串中最長數字長度。
問題描述:我們需要找到數字的長度,即字串中連續數字字元的長度。
讓我們舉個例子來理解這個問題:
輸入:str = “code001tutorials34124point”
輸出:34124
解釋:
字串中的數字是
001 - 長度為3
34124 - 長度為5
解決方案
解決這個問題的一個簡單方法是遍歷字串並找到數字的長度及其起始索引。我們將為字串中的每個數字儲存其起始位置和字元計數。最後,返回該數字。
程式說明了解決方案的工作原理:
示例
#include <iostream>
using namespace std;
string findLongestNumber(string str, int l) {
int count = 0, max = 0, maxLenPos = -1, currPos, currLen, maxLen = 0;
for (int i = 0; i < l; i++) {
currPos = maxLenPos;
currLen = maxLen;
count = 0;
maxLen = 0;
if (isdigit(str[i]))
maxLenPos = i;
while (isdigit(str[i])) {
count++;
i++;
maxLen++;
}
if (count > max) {
max = count;
}
else {
maxLenPos = currPos;
maxLen = currLen;
}
}
return (str.substr(maxLenPos, maxLen));
}
int main() {
string str = "code001tutorials34124point";
int l = str.length();
cout<<"The longest length number in string is "<<findLongestNumber(str, l);
return 0;
}輸出
The longest length number in string is 34124
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP