PAT甲級 1038 Recover the Smallest Number(字符串處理)

完全按照柳婼大神思路寫的。
附鏈接:https://blog.csdn.net/liuchuo/article/details/52264827?locationNum=10&fps=1

思路

sort排序的bool函數cmp直接用 return a + b < b + a, 這樣比較a放在前面和b放在前面誰更大,保證其按照能使數字最小的形式排列。

注意

1.最終輸出時應該去掉前置0,用一個while(str.length() != 0 && str[0] == ‘0’) 循環和str.erase(str.begin())來刪除string類的前綴0
2.若刪除前置零之後str.length() == 0,則需要輸出0否則會不輸出
3.string類可直接通過+完成相加操作

附代碼:

#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
#include <map>
#define LL long long
using namespace std;

const int maxn = 1000 + 5;

vector<string> num;

bool cmp(string a, string b){
    return a + b < b + a;
}

int main(){
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; i++){
        string x;
        cin>>x;
        num.push_back(x);
    }
    sort(num.begin(), num.end(), cmp);
    string s;
    for(int i = 0; i < num.size(); i++){
        s += num[i];
    }
    while(s.length() != 0 && s[0] == '0')
        s.erase(s.begin());
    if(s.length() == 0) cout<<0;
    cout << s;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章