笔试强训Day16 字符串 基础算法 双指针

QR6 字符串替换

题目链接:字符串替换_牛客题霸_牛客网 (nowcoder.com)

思路:简单的字符串操作。

AC code:

class StringFormat 
{
public:
    string formatString(string A, int n, vector<char> arg, int m) 
    {
        string ans;
        int pos = 0;
        for(int i = 0; i < A.size(); i ++)
        {
            if(A[i] == '%')
            {
                ans += arg[pos++];
                i++;
                continue;
            }
            ans += A[i];
        }
        
        for(; pos < arg.size(); pos++)
            ans += arg[pos];

        return ans;
    }
};

[编程题]神奇数

题目链接:神奇数_牛客笔试题_牛客网 (nowcoder.com)

思路:

AC了没写个位数的情况, 注意next_permutation的返回值,若字典序没变大,则会返回0,

比如91 如果写dowhile循环的话 91 变成 19 会返回0 没法继续循环 ,加个特判即可。

AC code:

#include <iostream>
#include<string>
#include<algorithm>
using namespace std;
int n, m;
int ans;
string a;

bool check(int x) {
    
    if(x < 2) return 0;
    
    for (int i = 2; i <= x / i; i ++)
        if (x % i == 0)
            return 0;
    return 1;
}

int main() {
    cin >> n >> m;

    for (int i = n; i <= m; i ++) {
        a = to_string(i);
        int cnt = 0;
        while (1) {
            if (cnt == 2) break;

            if (a[0] != '0') {
                int x = (a[0] - '0') * 10 + a[1] - '0';

                if (check(x)) {
                    //cout << i << ' ';
                    ans++;
                    break;
                }
            }

            if (!next_permutation(a.begin(), a.end()))
                cnt++;
        }
    }
    cout << ans << endl;
    return 0;
}

HJ63 DNA序列

题目链接:DNA序列_牛客题霸_牛客网 (nowcoder.com)

思路:

题目中求 G 和 C 在字符串的比例 双指针暴力即可。

AC code:

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s, res = "";
    int n, ans = -1;
    cin >> s >> n;
    for (int i = 0; i < s.size(); i++)
    {
        int cnt = 0;
        string tmp = "";
        for (int j = i; j < s.size() && j < i + n; j++)
        {
            tmp += s[j];
            if (s[j] == 'G' || s[j] == 'C') cnt++;
        }
        if (cnt > ans) res = tmp, ans = cnt;
    }
    cout << res << endl;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值