Description
Given a string containing only 'A' - 'Z', we could encode it using the following method:
1. Each sub-string containing k same characters should be encoded to "kX" where "X" is the only character in this sub-string.
2. If the length of the sub-string is 1, '1' should be ignored.
Input
The first line contains an integer N (1 <= N <= 100) which indicates the number of test cases. The next N lines contain N strings. Each string consists of only 'A' - 'Z' and the length is less than 10000.
Output
For each test case, output the encoded string in a line.
Sample Input
2
ABC
ABBCCC
Sample Output
ABC
A2B3C
#include <iostream>
using namespace std;
int main(){
int N;
cin>>N;
char a[100000]={0};
while(N--){
int i,j,b=1,c=0,k;
cin>>a;
for(j=0;a[j]!='\0';j++){
if(a[j]==a[j+1]){
b++;}
else{
if(b>1){
a[j-b+1]=(char)('0'+b);
b=1;} }}
for(j=0;a[j]!='\0';j++){
if(a[j]==a[j+1]){
for(k=j;a[k]!='\0';k++)
a[k]=a[k+1];
j=j-1;}}
cout<<a;
if(N)
cout<<endl;} }
找錯
uj5u.com熱心網友回復:
char a[100000]={0}; // 這里a陣列大小是要求的10倍吧。 區域變數的陣列不能太大, 特別大的就放成全域變數。if(a[j]==a[j+1]) // 這里j+1會不會越界
a[j-b+1]=(char)('0'+b); // 這里b如果大于9怎么辦
uj5u.com熱心網友回復:
謝謝。。。。。。。。。uj5u.com熱心網友回復:
在LZ的代碼上改了一下,修改點在注釋里int main() {
int N,n;
cin>>N;
char r[100][10001]; //答案要求輸入完后結果統一輸出,所以結果應該保存在一個二維陣列里
char a[10001]={0}; //沒必要在a的基礎上去做處理,a只是單純的接收輸入即可,所以長度為10001就好(因為最大不超過10000)
char t[6] = {};//用于把統計的數字變為字串,最大不超過5位數,所以長度6即可
for (n=0; n<N; n++) {
int i,j,b=1,k=0;
cin>>a;
memset(t, '\0', sizeof(t));
for(j=0;a[j]!='\0';j++){
if(a[j]==a[j+1]){//這里可以不擔心陣列越界,因為j回圈到最后一個字符時a[j+1]只是為字串結束符,下一個字符就退出回圈了
b++;
} else {
if(b>1){ //如果b大于1
sprintf(t, "%d", b); //則把b轉成字符
for (i=0; t[i]!='\0'; i++) { //然后先保存b
r[n][k++] = t[i];
}
r[n][k++] = a[j];//再保存字符
b=1;
} else {
r[n][k++] = a[j]; //否則直接保存字符
}
}
}
r[n][k] = '\0'; //結果的最后設定字串結束符
getchar();
}
for(n=0; n<N; n++)
cout<<r[n]<<endl; //列印
return 0;
}
uj5u.com熱心網友回復:
整了個原地修改的, 不借助中間陣列的int main() {
int N;
cin>>N;
char a[10000]={0}; // he length is less than 10000. 不用多給一個
while(N--){
int i=0,j=1,b=1;
cin>>a;
int Len = (int) strlen(a);
for(; j<=Len; ){ // 必須借助最后一個0字符才管用
if(a[i]==a[j]){ // i指向當前有效的最后一個字符,j指向當前處理到的字符
++b; ++j;
} else{
if(b>1){
char ch = a[j-1]; // I+1到j-1這個范圍是重復的字串,保存j-1是防止sprintf覆寫它
sprintf(a+i, "%d", b); // 直接輸出到a陣列里曼
while (a[i]!='\0')++I; // 找到輸出的數字后面的空位
a[i] = ch; // 把重復的字母放到這個空位上,剛好。
b = 1;
} else {
a[++i] = a[j++]; // i依然是最后一個有效的字符, 注意是++i,不是i++
}
}
}
cout<< a;
if(N) cout<<endl;
}
}
uj5u.com熱心網友回復:
嗯,謝謝,我已經ac了轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/143484.html
標籤:C++ 語言
上一篇:x01.paint: 繪圖程式
