python編程題-拼接最小字典序

來源:互聯網
上載者:User

標籤:python shell 編程練習

題目來源:牛客網

對於一個給定的字串數組,請找到一種拼接順序,使所有小字串拼接成的大字串是所有可能的拼接中字典序最小的。

給定一個字串數組strs,同時給定它的大小,請返回拼接成的串。

測試範例:

["abc","de"],2
"abcde"


python

代碼

# -*- coding:utf-8 -*-class Prior:    def findSmallest(self, strs, n):        # write code here        resstr = ""        for i in xrange(1,len(strs)):            for j in xrange(0,i):                if(strs[i]+strs[j])<(strs[j]+strs[i]):                    strs[i],strs[j] = strs[j],strs[i]        return ‘‘.join(strs)


shell實現

代碼

#/bin/bash#by xianwei#2017-9-4cat <<EOF題目對於一個給定的字串數組,請找到一種拼接順序,使所有小字串拼接成的大字串是所有可能的拼接中字典序最小的。給定一個字串數組strs,同時給定它的大小,請返回拼接成的串。測試範例:["abc","de"],2"abcde"EOFa=("kid" "yqt" "i" "k")for((i=0;i<${#a[*]};i++))do  for((j=0;j<i;j++))  do    if [[ "${a[$i]}${a[$j]}" < "${a[$j]}${a[$i]}" ]]    then        tmp=${a[$i]}echo $tmp        a[$i]=${a[$j]}        a[$j]=$tmp    fi  donedoneecho ${a[*]}



C++實現

代碼

class Prior {public:    string findSmallest(vector<string> strs, int n) {        // write code here        string A;        for (int i = 0; i < strs.size();i++)        {            for (int j = i; j < strs.size(); j++)            {                if ((strs[i] + strs[j])>(strs[j] + strs[i]))//假如k+kid > kid +k,就交換                    swap(strs[i],strs[j]);            }        }        for (int i = 0; i < strs.size(); i++)        {            A = A + strs[i];        }        return A;    }};


本文出自 “從營運到開發” 部落格,請務必保留此出處http://237085.blog.51cto.com/227085/1962689

python編程題-拼接最小字典序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.