ในปัญหานี้ เราได้รับสตริง 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