1625. 最小字典序字串

中等 廣度優先搜索 深度優先搜索 字串 枚舉

思路

每次可以做的操作:

  1. 將奇數位的數字加上 a % 10
  2. 或是向右輪轉 b 位 由於數據規模很小,可以暴力搜索出所有可能的情況求解,(當然也可以用數學推導公式加速)。

模擬題目敘述便能求解。

程式碼

class Solution {
public:
    string findLexSmallestString(string s, int a, int b) {
        int n = s.length();
        unordered_map<string, bool> umap;
        string res = s;
        auto dfs = [&](this auto&&dfs, string cur) {
            if(umap.find(cur) != umap.end()) return; // 終止條件, 已經搜索過。
            umap[cur] = true;
            // 輪轉
            string next = cur.substr(b) + cur.substr(0, b);
            res = min(res, next);
            dfs(next);
            // 置換
            next = cur;
            for(int i = 1; i < n; i += 2) {
                next[i] = (((next[i] - '0') + a) % 10) + '0';
            }
            res = min(res, next);
            dfs(next);
        };
        dfs(res);
        return res;
    }
};

複雜度分析

  • 時間複雜度:O(n2)O(n^2)
  • 空間複雜度:O(n)O(n)

顯示設定

背景線條
顯示背景網格線條
懸停發光
滑鼠懸停時顯示霓虹效果
聚光燈
跟隨滑鼠的聚光燈效果
背景透明度
開啟透明玻璃效果
主題顏色
自訂主要顏色