檢查是否可以透過反轉任何子字串使字串按字典序變小


在C++中,我們有一個內建的reverse()函式,用於反轉子字串以檢查字串是否可以按字典序變小。字典序是指按字典順序對單詞的字元進行排序。

讓我們以一個字串為例,來檢查是否按字典序變小。

  • 我們將比較這兩個單詞以檢查按字典序較小的單詞,並取兩個字串,即“apple”“army”。這兩個字串的第一個字母都是“a”。當我們移動到檢查兩個字母的第二個字元時,“p”在字母順序上位於“r”之前。因此,apple按字典序小於army

  • 在字串“tutorialspoint”中,反轉子字串“oria”得到“airo”,它按字典序較小。然後最終字串寫成“tutairolspoint”

  • 在字串“tutorix”中,反轉子字串“tori”得到“irot”,它按字典序較小,因為第一個子字串的開頭是't',第二個子字串是'i'。然後'i'在字母順序上位於't'之前,因此它使'irot'按字典序小於'tori'。然後最終字串寫成“tuirotx”

我們再舉一個字串的例子,例如“acwz”

語法

reverse( str_name.begin(), str_name.end() )

解釋

reverse函式是C++標準庫的一部分,它接受兩個引數“str_name.begin()”“str_name.end()”

  • str_name是使用者建議的字串名稱。

  • begin()end()是在reverse函式中使用的預定義內建函式。begin函式的作用是返回一個指向輸入字串第一個字元的迭代器。end函式的作用是返回一個指向輸入字串最後一個字元之前一個位置的迭代器。

請注意,reverse函式不返回任何值,因為它會就地修改容器(str_name)。

演算法

  • 首先,我們將使用三個必要的標頭檔案,即iostream、string和include<algorithm>,並宣告std名稱空間。

  • 我們將從main函式開始程式,在其中宣告一個名為'str'的字串變數,並在其中儲存字串'tutorialspoint'。然後,我們將宣告布林變數'isReverse''false',以指示給定字串未反轉且處於原始形式。

  • 然後,我們將建立兩個巢狀的for迴圈來檢查'str'的每個可能的子字串。然後將子字串儲存在名為'temp'的臨時字串中。

  • 之後,我們呼叫'reverse()'函式來反轉儲存在'temp'變數中索引'i''j'之間的子字串。

  • 稍後建立一個if語句,透過比較變數'temp''str'來檢查反轉後的字串是否按字典序較小。

  • 編譯器將比較變數temp和str。如果兩者相等,則變數'isReverse'將設定為true,並將中斷if語句。

  • 現在,我們將檢查isReverse的值,如果為true,它將列印if條件的語句,否則列印else條件的語句。

  • 退出程式。

示例

在這個程式中,我們將瞭解如何透過反轉任何子字串使字串按字典序變小。

#include <iostream>
#include <string>
#include <algorithm> 
using namespace std;
int main() {
   string str = "tutorialspoint";
   // User can change this to test other strings such as acwz, groffer, etc
   bool isReverse = false; // it is used to indicate whether or not a substring has been found in the original string “str”.


   // use the loop through all possible substrings of str
   for (int i = 0; i < str.length(); i++) {
      for (int j = i+1; j < str.length(); j++) {
         string temp = str; 
         // create new temporary variable to store the value of str.
         // reverse the substring of i and j
         reverse ( temp.begin() + i, temp.begin() + j + 1 ); 
         // reverse function follow the header file name as <algorithm>
         if (temp < str) { 
            // Check whether the reversed string is lexicographically smaller
            isReverse = true;
            break;
         }
      }
   }
   if ( isReverse ) {
      cout << "Yes, this is lexicographically smaller by reversing a  substring." << endl;
   } else {
      cout << "No, this is not lexicographically smaller by reversing a substring." << endl;
   }
   return 0;
}

輸出

如果我們輸入值“tutorialspoint”,我們將得到以下結果:

Yes, this is lexicographically smaller by reversing a  substring.

如果我們輸入值“acwz”,我們將得到以下結果:

No, this is not lexicographically smaller by reversing a substring.

結論

我們看到了如何使用字串變數來計算透過反轉任何子字串按字典序較小的字串。然後我們將字串變數設定為臨時變數。然後我們使用預定義函式“reverse()”來反向計算字典序單詞。接下來,我們透過比較變數temp和str來檢查按字典序較小的字串並得到結果。

更新於:2023年4月20日

590 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告