854. 相似度为 K 的字符串

代码实现(A*算法)
class Solution {
private:
int minSwap(string cur, string s2) {
int cnt = 0;
for (int i = 0; i < cur.size(); i++) {
cnt += (s2[i] != cur[i]);
}
return (cnt + 1) / 2;
}
public:
int kSimilarity(string s1, string s2) {
typedef tuple<int, int, int, string> State;
priority_queue<State, vector<State>, greater<State>> pq;
unordered_set<string> visited;
pq.push({0, 0, 0, s1});
int n = s1.size();
while (!pq.empty()) {
auto [_, cost, pos, cur] = pq.top();
pq.pop();
if (cur == s2) return cost;
while (pos < n && cur[pos] == s2[pos]) pos++;
for (int j = pos + 1; j < n; j++) {
if (cur[j] != s2[j] && cur[j] == s2[pos]) {
swap(cur[j], cur[pos]);
if (!visited.count(cur)) {
visited.emplace(cur);
pq.push({cost + 1 + minSwap(cur, s2), cost + 1, pos + 1, cur});
}
swap(cur[j], cur[pos]);
}
}
}
return -1;
}
};
2075. 解码斜向换位密码

代码实现(模拟)
class Solution {
public:
string decodeCiphertext(string encodedText, int rows) {
if (!encodedText.size()) return "";
int n = encodedText.size();
int cols = n / rows;
string ans = "";
int steps = cols + 1;
int pos = -1;
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
pos = i + j * steps;
if (pos > n - 1) break;
ans += encodedText[pos];
}
}
int endPos = ans.size() - 1;
while (ans[endPos] == ' ') endPos--;
return ans.substr(0, endPos + 1);
}
};
2121. 相同元素的间隔之和

代码实现(数学)
class Solution {
public:
vector<long long> getDistances(vector<int>& arr) {
typedef pair<int, long long> state;
unordered_map<int, stack<state>> mp;
int n = arr.size();
for (int i = 0; i < n; i++) {
if (!mp.count(arr[i])) {
mp[arr[i]].push({i, 0});
continue;
}
mp[arr[i]].push({i, mp[arr[i]].top().second + mp[arr[i]].size() *
(i - mp[arr[i]].top().first)});
}
vector<long long> ans(n);
for (auto it = mp.begin(); it != mp.end(); it++) {
stack<state>& st = it->second;
auto [nexPos, nexCnt] = st.top();
ans[nexPos] = nexCnt;
n = st.size();
st.pop();
while (!st.empty()) {
auto [pos, cnt] = st.top();
nexCnt = nexCnt + (n - 2 * st.size()) * (nexPos - pos);
nexPos = pos;
ans[nexPos] = nexCnt;
st.pop();
}
}
return ans;
}
};