Alphabetical Substrings

Assume s is a string of lower case characters.

Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, ifs = 'azcbobobegghakl', then your program should print

Longest substring in alphabetical order is: beggh

In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print

Longest substring in alphabetical order is: abc

s='abcbcd'

count=1
result=s[0]
while s:
    newcount=1
    newresult=''
    i=0
    while i+1<len(s):
        if ord(s[i])<=ord(s[i+1]):
            newresult+=s[i+1]
            newcount+=1
        else:
            break
        i+=1
    if newcount>count:
        count=newcount
        result=s[0]+newresult
    s=s[i+1:]
print result





```c++ #include <iostream> #include <string> using namespace std; int main() { string word1, word2, word3; string sorted_words, concat_words; // ask user for three words cout << "Enter three words: "; cin >> word1 >> word2 >> word3; // sort the words in alphabetical order if (word1 <= word2 && word1 <= word3) { sorted_words = word1; if (word2 <= word3) { sorted_words += " " + word2 + " " + word3; } else { sorted_words += " " + word3 + " " + word2; } } else if (word2 <= word1 && word2 <= word3) { sorted_words = word2; if (word1 <= word3) { sorted_words += " " + word1 + " " + word3; } else { sorted_words += " " + word3 + " " + word1; } } else { sorted_words = word3; if (word1 <= word2) { sorted_words += " " + word1 + " " + word2; } else { sorted_words += " " + word2 + " " + word1; } } // concatenate the words in alphabetical order if (word1 <= word2 && word1 <= word3) { concat_words = word1; if (word2 <= word3) { concat_words += word2 + word3; } else { concat_words += word3 + word2; } } else if (word2 <= word1 && word2 <= word3) { concat_words = word2; if (word1 <= word3) { concat_words += word1 + word3; } else { concat_words += word3 + word1; } } else { concat_words = word3; if (word1 <= word2) { concat_words += word1 + word2; } else { concat_words += word2 + word1; } } // output the sorted and concatenated words cout << "Sorted words: " << sorted_words << endl; cout << "Concatenated words: " << concat_words << endl; return 0; } ``` Sample output: ``` Enter three words: apple dog cat Sorted words: apple cat dog Concatenated words: applecatdog ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值