nowcoder 拼接最小字典序

本文介绍了一种算法,该算法通过自定义快速排序来确定字符串数组中元素的最佳拼接顺序,使得最终形成的字符串在字典序中是最小的。文章提供了具体的实现思路和Python代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

对于一个给定的字符串数组,请找到一种拼接顺序,使所有小字符串拼接成的大字符串是所有可能的拼接中字典序最小的。
给定一个字符串数组strs,同时给定它的大小,请返回拼接成的串。
测试样例:
[“abc”,”de”],2
“abcde”

思路

定义比较函数str1+str2<=str2+str1,然后自定义快排。

代码

class Prior:
    def mycmp(self, str1, str2):
        return str1 + str2 >= str2 + str1
    def partition(self, strs, begin, end):
        tmp = strs[begin]
        while begin < end:
            while begin < end and self.mycmp(strs[end], tmp):
                end -= 1
            if begin < end:
                strs[begin] = strs[end]
            while begin < end and self.mycmp(tmp, strs[begin]):
                begin += 1
            if begin < end:
                strs[end] = strs[begin]
        strs[begin] = tmp
        return begin
    def sort(self, strs, begin, end):
        if begin < end:
            parti = self.partition(strs, begin, end)
            self.sort(strs, begin, parti)
            self.sort(strs, parti + 1, end)
    def findSmallest(self, strs, n):
        # write code here
        self.sort(strs, 0, n - 1)
        return ''.join(strs)
### 关于最小字典序算法的概念与实现 #### 最小字典序的核心概念 最小字典序是指在一个排列集合中找到按字母顺序最早的一个排列。对于字符串数组而言,其目标是最小拼接后的整体字典序。通常采用贪心策略解决此类问题,通过两两比较字符串的不同组合方式来决定最优的前后位置关系。 一种有效的排序策略是基于字符串之间的相对次序判断:如果 `x+y` 的字典序小于等于 `y+x` 的字典序,则优先放置 `x` 在前[^1]。这种方法能够有效处理特殊情况下的错误排序,例如 `[ba, b]` 这样的例子。 以下是具体实现方法: --- #### Python 实现代码示例 ```python from functools import cmp_to_key def compare(x, y): """自定义比较函数""" if x + y < y + x: return -1 elif x + y > y + x: return 1 else: return 0 def smallest_lexicographical_concatenation(strs): """ 使用贪心算法计算字符串数组能拼接出的最小字典序结果 参数: strs (list): 字符串列表 返回: str: 拼接后的最小字典序字符串 """ sorted_strs = sorted(strs, key=cmp_to_key(compare)) result = ''.join(sorted_strs) return result # 测试用例 if __name__ == "__main__": test_cases = [["ba", "b"], ["abc", "de", "fgh"]] for case in test_cases: print(f"Input: {case}, Output: '{smallest_lexicographical_concatenation(case)}'") ``` 上述代码实现了基于贪心算法的最小字典序拼接逻辑。其中核心是比较任意两个字符串连接后的效果,并以此为基础重新调整整个字符串数组中的元素顺序[^3]。 --- #### C++ 实现代码示例 ```cpp #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; // 自定义比较器 bool customComparator(string& a, string& b) { return (a+b).compare(b+a) < 0; } string findSmallestLexConcat(vector<string>& strs) { sort(strs.begin(), strs.end(), customComparator); string result = ""; for(auto s : strs){ result += s; } return result; } int main() { vector<string> input = {"ba", "b"}; cout << "Result: " << findSmallestLexConcat(input) << endl; return 0; } ``` 此C++版本同样遵循相同原则,即通过定制化的比较器完成对原始数据结构的操作并最终获得期望输出。 --- #### 特殊场景扩展思考 当涉及更复杂的约束条件时(如允许有限次数内的字符交换),则需引入动态规划或者模拟技术进一步优化解决方案[^4]。而在某些特定领域应用下(如同二分图匹配问题中的路径选择),还可能结合其他高级技巧共同作用达成目的[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值