公式
B - typo 解説 by en_translator
We can check if \(S\) and \(T\) are the same without performing any operation, or if \(S\) and \(T\) coincides when the \(i\)-th and \((i+1)\)-th characters are swapped for each \(i=1,2,\ldots,(\)length of \(S)-1\).
The time complexity is \(O(N^2)\), where \(N=(\)length of \(S)\).
Sample code (Python)
S = list(input())
T = list(input())
ans = "No"
if S == T:
ans = "Yes"
for i in range(len(S)-1):
S[i],S[i+1] = S[i+1],S[i]
if S == T:
ans = "Yes"
S[i],S[i+1] = S[i+1],S[i]
print(ans)
With a little more twist, the time complexity can be decreased to \(O(N)\).
Sample code (C++)
#include<bits/stdc++.h>
using namespace std;
int main(){
string S,T; cin >> S >> T;
string ans = "No";
if(S == T) ans = "Yes";
for(int i=0; i<S.size(); i++){
if(S[i] != T[i]){
if(0 < i){
swap(S[i-1],S[i]);
if(S == T) ans = "Yes";
swap(S[i-1],S[i]);
}
if(i+1 < S.size()){
swap(S[i],S[i+1]);
if(S == T) ans = "Yes";
swap(S[i],S[i+1]);
}
break;
}
}
cout << ans << endl;
}
投稿日時:
最終更新: