求最長數字串(華爲勇敢星筆試第一題)

因爲當時做筆試的時候,是從後向前做的(第三題是大數相乘,思路比較清晰)

第二題卡了很久,所以這題的時間不是很充裕,就用了最直觀的方法寫的

當時沒AC,通過率百分之80,現在想來應該是輸出空的時候有問題吧,日後還會精進,這次就先拿來丟人現眼一下吧。

思路是:

/*得到字符串,定義一個bool,控制是否開始累加,如果前面的爲字符,後面的爲數字,則開始
 如果前面爲數字,後面爲字符則結束,定義一個vector用來存開始和長度,定義一個N爲vector的大小
 每當結束時,N+1*/

 void CalLong(string input) {
bool IsNum = false;
string value = input;
vector<pair<int, int>> StartAndCount;
int Count = 0;
int n = value.size()-1;
int NUM = 0;
if (value[0] – ‘0’ <= 9 && value[0] – ‘0’ >= 0) {
IsNum = true;
StartAndCount.push_back(make_pair(0,0));
}
for (int i = 1; i <= n; i++) {

if (value[i] – ‘0’ <= 9 && value[i] – ‘0’ >= 0 ) {
if (value[i – 1] – ‘0’ > 9 || value[i – 1] – ‘0’ < 0)
        IsNum = true;

}
if (IsNum) {
Count++;
}
if (value[i] – ‘0’ <= 9 && value[i] – ‘0’ >= 0 ) {
if (value[i + 1] – ‘0’ > 9 || value[i + 1] – ‘0’ < 0) {
IsNum = false;
StartAndCount.push_back(make_pair(0, 0));
StartAndCount[NUM].first = i;
StartAndCount[NUM].second = Count;
Count = 0;
NUM++;
}
}

}
int num = 0;
for (int i = 0; i < StartAndCount.size(); i++) {
int max = StartAndCount[0].second;
if (max < StartAndCount[i].second) {
max = StartAndCount[i].second;
num = i;
}

}
if (Count > 0) {
cout << value.substr(StartAndCount[num].first + 1 – StartAndCount[num].second, StartAndCount[num].second) << “,” << StartAndCount[num].second << endl;
}
else {
cout << “\”\””<<endl;
}
 }
 int main() {
string input;
cin >> input;
CalLong(input);
system(“pause”);
}

点赞