赞
踩
5apple appleeapple appeapple bppleapplee bppleapple apple
similarsimilarsimilarnot similarsimilar
解析:
详见代码:
- #include <iostream>
- #include <string>
- using namespace std;
- bool isSimilar(string A, string B) {
- int m = A.size(), n = B.size();
- if (abs(m - n) > 1) return false;
- if (m == n) {
- int diff = 0;
- for (int i = 0; i < m; ++i) {
- if (A[i] != B[i]) {
- if (++diff > 1) return false;
- }
- }
- return diff <= 1;
- } else {
- string& shorter = (m < n) ? A : B;
- string& longer = (m < n) ? B : A;
- int i = 0, j = 0;
- int diff = 0;
- while (i < shorter.size() && j < longer.size()) {
- if (shorter[i] != longer[j]) {
- if (++diff > 1) return false;
- ++j;
- } else {
- ++i;
- ++j;
- }
- }
- return true;
- }
- }
- int main() {
- int T;
- cin >> T;
- while (T--) {
- string A, B;
- cin >> A >> B;
- if (isSimilar(A, B)) {
- cout << "similar" << endl;
- } else {
- cout << "not similar" << endl;
- }
- }
- return 0;
- }
另一种解法:
- #include <iostream>
- #include <string>
- using namespace std;
- bool isSimilar(string A, string B) {
- int m = A.size(), n = B.size();
- if (abs(m - n) > 1) return false;
- if (A==B) return true;
- int cnt=0;
- for(int i=0;i<min(m,n);i++){
- if (A[i]==B[i]){
- cnt++;
- }else{
- break;
- }
- }
- for(int i=m-1,j=n-1;i>=0&&j>=0;i--,j--){
- if (A[i]==B[j]){
- cnt++;
- }else{
- break;
- }
- }
- return cnt>=max(m,n)-1;
- }
- int main() {
- int T;
- cin >> T;
- while (T--) {
- string A, B;
- cin >> A >> B;
- if (isSimilar(A, B)) {
- cout << "similar" << endl;
- } else {
- cout << "not similar" << endl;
- }
- }
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。