C++交替大小寫字串排序


字串是字元陣列。這個問題是將字串的元素按交替大小寫排序。

問題描述 - 交替大小寫字串排序,是一個問題,其中我們得到一個無序字串,其中包含混合的大寫和小寫字元,我們需要以大寫和小寫字元交替出現的方式排序這個字串,但要保持排序。

讓我們舉個例子來更好地理解這個主題:

Input : aFegrAfStRzsV
Output : AaFeRfSgVrstz
Explanation :
Upper case characters : A F R S V
Lower case characters : a e f g r s t z

兩者都已排序,因此我們現在可以交替排列它們。

現在,既然我們已經理解了這個問題。讓我們建立一個解決方案。一種方法是建立按排序順序排列的大寫和小寫字母陣列,然後將它們交替排列到最終字串中。我們根據此邏輯建立了一個演算法。

演算法

Step 1 : In an array lowercount[] add all lowercase characters in sorted order.
Step 2 : In an array uppercount[] add all uppercase characters in sorted order.
Step 3 : Create the final string using alternate values from both arrays.
Step 4 : Print the result array.

示例

 線上演示

#include <iostream>
using namespace std;
#define MAX 26
void alternateULSort(string& s) ;
int main(){
   string str = "aFegrAfStRzsV";
   cout<<"The unsorted string is : "<<str;
   cout<<"\nThe alternate lower upper sorted string is ";
   alternateULSort(str);
   cout << str << "\n";
}
void alternateULSort(string& s){
   int n = s.length();
   int lowerCount[MAX] = { 0 }, upperCount[MAX] = { 0 };
   for (int i = 0; i < n; i++) {
      if (isupper(s[i]))
         upperCount[s[i] - 'A']++;
      else
         lowerCount[s[i] - 'a']++;
   }
   int i = 0, j = 0, k = 0;
   while (k < n) {
      while (i < MAX && upperCount[i] == 0)
         i++;
      if (i < MAX) {
         s[k++] = 'A' + i;
         upperCount[i]--;
         }
      while (j < MAX && lowerCount[j] == 0)
         j++;
      if (j < MAX) {
         s[k++] = 'a' + j;
         lowerCount[j]--;
      }
   }
}

輸出

The unsorted string is : aFegrAfStRzsV
The alternate lower upper sorted string is AaFeRfSgVrstz

更新於:2019年10月16日

494 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告