【发布时间】:2014-11-13 16:53:43
【问题描述】:
我正在做alternating characters problem。
问题:
Shashank 喜欢连续字符不同的字符串。 例如,他喜欢ABAA,而他不喜欢ABAA。给定一个 仅包含字符 A 和 B 的字符串,他想将其更改为 他喜欢的一根弦。为此,他可以删除字符 在字符串中。
您的任务是找出所需删除的最少数量。
输入格式第一行包含一个整数T,即 测试用例。接下来的 T 行每行包含一个字符串。
输出格式打印每个测试所需的最少步骤数 案例。
约束
1≤T≤10 1≤字符串长度≤105
我的代码:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t,i,j;
scanf("%d", &t);
char line[100000];
for(i=0; i < t; i++){
//get string from user
fgets(line, sizeof(line), stdin);
//loop line and greedily solve this
int deletions = 0;
if(strlen > 0){
char currentChar = line[0];
for(j=1; j < strlen(line); j++){
if(currentChar == line[j]){
deletions++;
}else{
currentChar = line[j];
}
}
}
printf("%d\n", deletions);
//empty string
memset(line,0,strlen(line));
}
return 0;
}
输入:
5
AAAA
BBBBB
ABABABAB
BABABA
AAABBB
我的输出:
0
3
4
0
0
预期输出:
3
4
0
0
4
我不是 C 专家,所以如果这是一个明显的问题,我很抱歉。似乎我的fgets 在不应该的时候捕获了一个空行。我的猜测是它与scanf 有关。但是,我不知道为什么,也不知道如何解决?
【问题讨论】:
-
if(strlen > 0)-->if(strlen(line) > 0) -
@weathervane 好收获!
标签: c