B. Complete the Word (尺取法)

博客给出一道字符串替换题目的链接及大意,即字符串中 '?' 可用A->Z替换,判断能否得到连续A->Z子序列。指出该题与Leetcode 1004类似,采用尺取法解题,给出指针移动思路,还给出AC代码的转载链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://codeforces.com/problemset/problem/716/B

 

题目大意:字符串中的 '?' 可以用A->Z任何一个来替换 问能不能通过替换使字符串有一个连续的A->Z的子序列   可以就输出  不可以就输出-1

 

思路:

这道题和 Leetcode 1004 很像,不同的就是这里的?都可以替换掉

同样还是考虑尺取法。 让第一个指针i 从0开始往后走(因为要确保有26个序列,所以i到len-26必须停止。因为如果再往后走肯定就没有26个了,没必要去查找)

第二个指针j从i开始往后走26个就可以了

 

AC代码:

 1 #include <cstdio>
 2 #include <string>
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <cstdbool>
 6 #include <string.h>
 7 #include <math.h>
 8 
 9 
10 using namespace std;
11 
12 char s[1000005];
13 int vis[30];
14 
15 int main()
16 {
17     while (cin >> s)
18     {
19         bool flag = true;
20         int len = strlen(s);
21         if (len < 26) {
22             printf("-1\n");
23             continue;
24         }
25         for (int i = 0; i <= len - 26 && flag; i++)
26         {
27             int cnt1 = 0,cnt2 = 0;
28             memset(vis,0, sizeof(vis));
29             for (int j=i;j<i+26;j++)
30             {
31                 if (s[j]>='A' && s[j]<='Z')
32                 {
33                     vis[s[j]-'A']++;
34                 }
35                 else
36                     cnt2++;   //问号数目
37             }
38             for (int j=0;j<26;j++)
39             {
40                 if (vis[j]==1)
41                     cnt1++;
42             }
43             if (cnt1 + cnt2 == 26)
44             {
45                 int t = 0;
46                 for (int j=i;j<i+26;j++)
47                 {
48                     if (s[j] == '?')
49                     {
50                         for (;t<26;t++)
51                         {
52                             if (vis[t] == 0)
53                             {
54                                 s[j] = 'A' + t;
55                                 t++;
56                                 break;
57                             }
58                         }
59                     }
60                 }
61                 flag = false;
62             }
63         }
64         for (int i=0;i<len;i++)
65         {
66             if (s[i] == '?')
67             {
68                 s[i] = 'A';
69             }
70         }
71         if (flag)
72             printf("-1\n");
73         else
74             cout << s << endl;
75 
76     }
77 }

 

转载于:https://www.cnblogs.com/-Ackerman/p/11168638.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值