Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

หาตัวเลขที่ยาวที่สุดในสตริงใน C++

โจทย์

ได้รับสตริง str ประกอบด้วยตัวอักษรและตัวเลข ทางเราต้อง หาตัวเลขที่มีความยาวมากที่สุดในสตริง

ตัวอย่าง

Input: str = "code001tutorials34124point"

Output: 34124

อธิบาย: ตัวเลขในสตริง: 001 (ยาว 3), 34124 (ยาว 5)

แนวทางแก้ปัญหา

ท่องสตริงนับความยาวของตัวเลขติดต่อกัน (Consecutive Digits) เก็บตำแหน่งเริ่มต้นและความยาวสูงสุด แล้วคืนค่าส่วนของสตริง (substring)

โปรแกรมตัวอย่าง

#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