贪心算法-拼接字符串使得字典顺序最小问题

题目1

给定一个由字符串组成的数组strs,必须把所有字符串拼接起来,返回所有可能的拼接结果中,字典序最小的结果

思路:对数组排序,排序规则是对a+b和b+a的字符串进行比较大小,返回较小的顺序放到数组中最后将数组累加即得

c 复制代码
public static String lowestString2(String[] strs) {
    if (strs == null || strs.length == 0) {
        return "";
    }
    Arrays.sort(strs, new StringCompartor());

    String res = "";
    for (int i = 0; i < strs.length; i++) {
        res += strs[i];
    }
    return res;
}

public static class StringCompartor implements Comparator<String> {

    @Override
    public int compare(String a, String b) {
        return (a + b).compareTo(b + a);
    }
}
相关推荐
武子康2 小时前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
lisw058 小时前
Dayhoff的PAM替换矩阵理论评介!
线性代数·算法·矩阵
一起学安全技术9 小时前
拆大模型 03|注意力的一句话版本:不用论文讲清 Attention
深度学习·算法·语言模型·transformer
Delightrs10 小时前
Rust LeetCode238 算法题解
开发语言·算法·rust
自信1504130575910 小时前
重生之从0开始学习c++之——vector-中篇
c++·学习·算法
GoAI21 小时前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
Pniubi1 天前
力扣54.螺旋矩阵
算法·leetcode·矩阵
choumou_M1 天前
算法_1:由浅入深学习快速排序QuickSort
学习·算法·排序算法
Coder_Shenshen1 天前
罗克韦尔ACD工程归档离线变量树解析
算法·c#