拼接最小字典序 --字符串数组



对于一个给定的字符串数组,请找到一种拼接顺序,使所有小字符串拼接成的大字符串是所有可能的拼接中字典序最小的。

给定一个字符串数组strs,同时给定它的大小,请返回拼接成的串。

测试样例:
["abc","de"],2
"abcde"

分析:该题实际上是对数组中的字符串排序,不过要注意特殊情况,比如“b”和“ba“,按字典序是”bba“这样的顺序,但实际上应该是”bab“整个数组字典序才是最小的。所以比较方式要改为比较s1+s2>s2+s1。


代码如下:

class Prior {
public:
    string findSmallest(vector<string> strs, int n) {
        assert((int)strs.size() == n && n >= 0);
        
        quick_sort_string(strs, 0, n-1);
        
        string res;
        for(int i=0; i<n; ++i)
        	res += strs[i];
        
        return res;
    }
private:
    static bool compare(const string& s1, const string& s2){
        return s1+s2 < s2+s1;
    }
    
    int random_range(const int begin, const int end){
        return random()%(end - begin) + begin;
    }
    
    int partition(vector<string>& strs, int low, int high,
                  bool (*cmp)(const string&, const string&)){
        int index = random_range(low, high);
        std::swap(strs[index], strs[high]);
        
        int small = -1;
        for(index=0; index<high; ++index){
            if(cmp(strs[index], strs[high])){  //注意strs[index]和strs[high]都是string类型
                ++small;
                if(small != index)
                    std::swap(strs[small], strs[index]);
            }
        }
        ++small;
        std::swap(strs[small], strs[high]);
        return small;
    }
    
    void quick_sort_string(vector<string>& strs, int low, int high){
        if(low < high){
            int middle = partition(strs, low, high, compare);
            quick_sort_string(strs, low, middle-1);
            quick_sort_string(strs, middle+1, high);
        }
    }                     
};







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值