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

题目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);
    }
}
相关推荐
We་ct21 小时前
LeetCode 300. 最长递增子序列:两种解法从入门到优化
开发语言·前端·javascript·算法·leetcode·typescript
wayz111 天前
Day 9 :随机森林调参与时间序列交叉验证
算法·随机森林·机器学习
️是781 天前
信息奥赛一本通—编程启蒙(3371:【例64.2】 生日相同)
开发语言·c++·算法
ZPC82101 天前
ROS2 快过UDP的方法
python·算法·机器人
周末也要写八哥1 天前
最长递增子序列典型应用题目详解
数据结构·算法
不会写DN1 天前
为什么map查找时间复杂度是O(1)?
算法·哈希算法·散列表
始三角龙1 天前
LeetCode hoot 100 -- 找到字符串中的所有字母异位词
算法·leetcode·职场和发展
abant21 天前
leetcode 45 跳跃问题2 很难的贪心
算法·leetcode·职场和发展
小糯米6011 天前
C语言指针3
c语言·数据结构·算法
ZPC82101 天前
ROS2 通信提速快过UDP
人工智能·算法·机器人