Cho chuỗi str chứa chữ cái và số. Nhiệm vụ: tìm số có độ dài lớn nhất trong chuỗi.
Mô tả: Tìm độ dài dãy số liên tiếp (chữ số) trong chuỗi.
Ví dụ:
Đầu vào: str = "code001tutorials34124point"
Đầu ra: 34124
Giải thích:
Các số trong chuỗi:
001 - độ dài 3
34124 - độ dài 5
Phương pháp giải
Duyệt chuỗi, đếm độ dài dãy số và vị trí bắt đầu. Lưu vị trí và độ dài lớn nhất, cuối cùng trả về chuỗi con đó.
Chương trình minh họa
Ví dụ
#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;
}
Kết quả
The longest length number in string is 34124