跳到正文

题解

8/13题解

Ten_shu_can约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年8月13日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 5 分钟

版本

  1. v1当前

第三题:

需找出字符串 s 和 s1 中,字符种类及数量的交集,使 s 变为 s1 的序列,求调整后 s 的最大长度。

C++
#include <bits/stdc++.h>
using namespace std;
string s,s1;
int a[30],a1[30];
int main(){
    cin>>s>>s1;//输入
    for(int i=0;i<s.size();i++){
     a[s[i]-'a']++;//将字符加入数组
    }
    for(int i=0;i<s1.size();i++){
     a1[s1[i]-'a']++;
    }
    int m=0;
    for(int i=0;i<=25;i++){
     m+=min(a[i],a1[i]);//计算相同数
    }
    cout<<m;
    return 0;
}

第四题:

需验证 ISBN 号码的识别码是否正确。识别码通过前 9 位数字求和取模 11 得到。若输入识别码正确输出 Right,否则输出正确 ISBN。

C++
#include<bits/stdc++.h>
using namespace std;
int num[15];
int main(){
    string word;
    cin>>word;// 提取数字
    num[0]=word[0]-'0';          
    num[1]=word[2]-'0';      
    num[2]=word[3]-'0';        
    num[3]=word[4]-'0';      
    num[4]=word[6]-'0';     
    num[5]=word[7]-'0';    
    num[6]=word[8]-'0';     
    num[7]=word[9]-'0';    
    num[8]=word[10]-'0';    
    a_real = num[0] + num[1]*2 + num[2]*3 + num[3]*4+ num[4]*5 + num[5]*6 + num[6]*7 + num[7]*8 + num[8]*9;
    a_real %= 11; // 计算
    if (a_real == 10) {
        if (word[12] == 'X') { // 模 11 为 10 时应为 'X'
            cout << "Right";
            a = 1;
        }
    } else if (a_real == word[12] - '0') { // 识别码为数字
        cout << "Right";
        a = 1;
    }

    // 识别码错误时,输出正确的 ISBN
    if (a != 1) {
        cout << num[0] << "-" << num[1] << num[2] << num[3] 
             << "-" << num[4] << num[5] << num[6] << num[7] << num[8] << "-";
        if (a_real == 10) cout << "X";
        else cout << a_real;
    }
    return 0;
}

第五题:

统计字符串拷贝次数。string 会触发字符拷贝,string_view 不会。需判断每行代码,计算拷贝的次数。

C++
#include<bits/stdc++.h>
using namespace std;
map<string, int> mp; // 存储变量名
string a, b;
int sub(string t, int op) {
    int len = t.size();
    int index = 0;
    string temp = "", temp1 = "";
    for (int i = 0; i < len; i++) {
        if (t[i] == '(') {//获取变量名
            index = i;
            break;
        }
        temp += t[i];
    }
    //提取内容
    for (int i = index + 1; i < len; i++) {
        if (t[i] == ')') break;
        temp1 += t[i]; //初始化内容
    }
    // 处理初始化内容
    if (temp1[0] == '\"') { // 字符串字面量
        mp[temp] = temp1.size() - 2; // 长度是去掉首尾引号后的长度
    } else {
        mp[temp] = mp[temp1]; // 复用已有变量的长度
    }

    // op=1 时返回长度,op=0 时返回 0
    if(op==1){
  return mp[temp];
 }else{
  return 0;
 }
}
int main() {
    int n; 
    cin >> n; // 程序行数
    int s = 0;
    for (int i = 1; i <= n; i++) {
        cin >> a >> b; 
        if (a == "string") {
            s += sub(b, 1); // string 类型,加次数
        } else {
            s += sub(b, 0); // string_view ,不加次数
        }
    }
    cout << s << endl; // 输出次数
    return 0;
}

第五题:

原文