LeetCode笔记(String,自定义排序*)

179 - 6

179. 最大数

在这里插入图片描述
自定义排序:通过比较两个字符串连接起来后的大小进行排序

// 12.04 
// 12.25
class Solution {
    static bool compare(int t1, int t2) {
        string a = to_string(t1);
        string b = to_string(t2);

        return a + b > b + a;
    }
public:
    string largestNumber(vector<int>& nums) {
        sort(nums.begin(), nums.end(), compare);
        
        string res;
        for(auto x : nums) {
            //cout << x << ' ';
            if(res == "0") res = "";
            res = res + to_string(x);
        }
        //cout << endl;
        return res;
    }
};

6. Z 字形变换

在这里插入图片描述
这里可以把二维数组简化位一维数组

// 12.33
// 12.49
// 可以优化成只用一维数组
class Solution {
public:
    string convert(string s, int numRows) {
        if(s.empty() || numRows == 1) return s;

        vector<vector<string>> tmp(numRows, vector<string>(1, ""));
        int k = 0, flag = 0;
        for(auto x : s) {
            if(!flag) {
                tmp[k++][0].push_back(x);
                if(k == numRows) {
                    k -= 2;
                    flag = 1;
                }
            } else {
                tmp[k--][0].push_back(x);
                if(k < 0) {
                    k += 2;
                    flag = 0;
                }
            }
        }

        string ans;
        for(auto x : tmp) {
            //cout << x[0] << endl;
            ans = ans + x[0];
        }
        return ans;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值