C++ 中分割連線字串


假設我們有一系列字串,我們可以將這些字串連線成一個迴圈,在迴圈中,對於每個字串,我們可以選擇是否反轉它。在所有可能的迴圈中,我們需要找到在切割迴圈後詞典序最大的字串,這將使迴圈字串變成一個普通字串。具體來說,為了找到詞典序最大的字串,我們需要經歷兩個階段:

將所有字串連線成一個迴圈,我們可以反轉一些字串或不反轉,並按照給定的順序連線它們。

在迴圈的任何位置進行切割並設定一個切割點,這將使迴圈字串變成一個從切割點開始的普通字串。我們的任務是在所有可能的普通字串中找到詞典序最大的一個。

因此,如果輸入類似於“abc”,“xyz”,則輸出將為“zyxcba”,因為我們可以得到像“-abcxyz-”,“-abczyx-”,“-cbaxyz-”,“-cbazyx-”這樣的迴圈字串,其中“-”用於表示迴圈狀態。答案字串來自第四個迴圈字串,我們可以在中間字元'a'處進行切割並得到“zyxcba”。

為了解決這個問題,我們將遵循以下步驟:

  • 定義一個函式 solve(),它將接收 idx、陣列 strs、rev 作為引數。

  • temp := strs[idx]

  • 如果 rev 不為零,則:

    • 反轉陣列 temp

  • str1 := 空字串

  • str2 := 空字串

  • 對於初始化 i := 0,當 i < idx 時,更新(i 加 1),執行:

    • str1 := str1 + strs[i]

  • 對於初始化 i := idx + 1,當 i < strs 的大小 時,更新(i 加 1),執行:

    • str2 := str2 + strs[i]

  • 對於初始化 k := 0,當 k < temp 的大小 時,更新(k 加 1),執行:

    • newOne := 從 temp 的索引 k 到結尾的子字串連線 str2 連線 str1 連線 temp 的索引 (0 到 k-1) 的子字串

    • 如果 ret 為空或 ret < newOne,則:

      • ret := newOne

  • 定義一個函式 findMax(),它將接收陣列 strs 作為引數。

  • 對於初始化 i := 0,當 i < strs 的大小 時,更新(i 加 1),執行:

    • temp := strs[i]

    • 反轉陣列 temp

    • strs[i] := (如果 strs[i] > temp,則 strs[i],否則 temp)

  • 從主方法執行以下操作:

  • ret := 空字串

  • findMax(strs)

  • 對於初始化 i := 0,當 i < strs 的大小 時,更新(i 加 1),執行:

    • solve(i, strs, false)

    • solve(i, strs, true)

  • 返回 ret

示例

讓我們看看以下實現以獲得更好的理解:

 線上演示

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string ret;
   void solve(int idx, vector <string > strs, bool rev){
      string temp = strs[idx];
      if (rev)
         reverse(temp.begin(), temp.end());
      string str1 = "";
      string str2 = "";
      for (int i = 0; i < idx; i++)
         str1 += strs[i];
      for (int i = idx + 1; i < strs.size(); i++)
         str2 += strs[i];
      for (int k = 0; k < temp.size(); k++) {
         string newOne = temp.substr(k) + str2 + str1 + temp.substr(0, k);
         if (ret == "" || ret < newOne) {
            ret = newOne;
         }
      }
   }
   void findMax(vector<string>& strs){
      for (int i = 0; i < strs.size(); i++) {
         string temp = strs[i];
         reverse(temp.begin(), temp.end());
         strs[i] = strs[i] > temp ? strs[i] : temp;
      }
   }
   string splitLoopedString(vector& strs) {
      ret = "";
      findMax(strs);
      for (int i = 0; i < strs.size(); i++) {
         solve(i, strs, false);
         solve(i, strs, true);
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<string> v = {"abc", "xyz"};
   cout << (ob.splitLoopedString(v));
}

輸入

{"abc", "xyz"}

輸出

zyxcba

更新於: 2020-11-16

471 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.