题解 | 小红的字符串修改

小红的字符串修改

https://www.nowcoder.com/practice/66e0054ff6b345afa47bcd4e8ceb72d7

#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
//将字符串S中的字母移动得到字符串t的子串(连续),求出移动的次数的最小值
//两个串的长度,对母串进行遍历,比较得出移动次数的最小值
int main() {
    string  s, t;
    cin >> s; //待替换的串
    cin >> t; //目标串
     int num1 = s.size();
    int num2 = t.size();
    int  minz = 1e5 + 5; //注意边界值,初始最小值要大于26乘以10的3次方


    for (int i = 0; i<= num2 - num1; i++) {
        //计算替换次数
        int sum = 0;
        for (int j = 0; j < num1; j++) {
            int temp1 = s[j] -'a';
        int temp2 = t[i+j] -'a'; 
            int item = abs(temp1- temp2);
            sum += min(item, 26-item);
        }
        minz = min(minz, sum);
    }
    cout << minz;
    return 0;
}

全部评论

相关推荐

评论
1
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务