LeetCode 第 211 場周賽
阿新 • • 發佈:2020-10-26
模擬 列舉
1 class Solution { 2 public: 3 int maxLengthBetweenEqualCharacters(string s) { 4 int n = s.size(); 5 int ans = -1; 6 for (int i = 0; i < n; i++) { 7 for (int j = i + 1; j < n; j++) { 8 if (s[i] == s[j]) { 9View Codeans = max(ans, j - i - 1); 10 } 11 } 12 } 13 return ans; 14 } 15 };
DFS + 剪枝
1 class Solution { 2 public: 3 string ans; 4 map<string, int> m; 5 void dfs(string s, int a, int b) { 6View Codeif (m[s]) return ; 7 m[s] = 1; 8 ans = min(ans, s); 9 string str = s; 10 for (int i = 1; i < str.size(); i += 2) { 11 int x = (str[i] - '0' + a) % 10; 12 str[i] = (x + '0'); 13 } 14 dfs(str, a, b); 15 str = s.substr(s.size() - b, b) + s.substr(0, s.size() - b); 16 dfs(str, a, b); 17 } 18 string findLexSmallestString(string s, int a, int b) { 19 ans = s; 20 dfs(s, a, b); 21 return ans; 22 } 23 };