字符串p型编码
- C 语言实现
- C++ 实现
- Java 实现
- Python 实现
💐The Begin💐点点关注,收藏不迷路💐
|
给定一个完全由数字字符(‘0’,‘1’,‘2’,…,‘9’)构成的字符串str,请写出str的p型编码串。例如:字符串122344111可被描述为"1个1、2个2、1个3、2个4、3个1",因此我们说122344111的p型编码串为1122132431;类似的道理,编码串101可以用来描述1111111111;00000000000可描述为"11个0",因此它的p型编码串即为110;100200300可描述为"1个1、2个 0、1个2、2个0、1个3、2个0",因此它的p型编码串为112012201320。
输入
输入仅一行,包含字符串str。每一行字符串最多包含1000个数字字符。
输出
输出该字符串对应的p型编码串。
样例输入
122344111
样例输出
1122132431
C 语言实现
#include <stdio.h>
#include <string.h>
// 函数用于生成p型编码串
void pEncoding(char str[]) {
int len = strlen(str);
int i, j;
for (i = 0; i < len; ) {
int count = 1;
// 统计连续相同字符的个数
for (j = i + 1; j < len && str[j] == str[i]; j++) {
count++;
}
// 输出字符个数和字符本身
printf("%d%c", count, str[i]);
i = j;
}
printf("\n");
}
int main() {
char str[1001];
// 读取输入字符串
scanf("%s", str);
pEncoding(str);
return 0;
}
C++ 实现
#include <iostream>
#include <string>
// 函数用于生成p型编码串
void pEncoding(const std::string& str) {
int len = str.length();
int i, j;
for (i = 0; i < len; ) {
int count = 1;
// 统计连续相同字符的个数
for (j = i + 1; j < len && str[j] == str[i]; j++) {
count++;
}
// 输出字符个数和字符本身
std::cout << count << str[i];
i = j;
}
std::cout << std::endl;
}
int main() {
std::string str;
// 读取输入字符串
std::cin >> str;
pEncoding(str);
return 0;
}
Java 实现
import java.util.Scanner;
public class PEncoding {
// 函数用于生成p型编码串
public static void pEncoding(String str) {
int len = str.length();
int i, j;
for (i = 0; i < len; ) {
int count = 1;
// 统计连续相同字符的个数
for (j = i + 1; j < len && str.charAt(j) == str.charAt(i); j++) {
count++;
}
// 输出字符个数和字符本身
System.out.print(count + "" + str.charAt(i));
i = j;
}
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
// 读取输入字符串并调用函数生成p型编码串
pEncoding(str);
}
}
Python 实现
str_input = input() # 读取输入字符串
result = ""
i = 0
while i < len(str_input):
count = 1
j = i + 1
while j < len(str_input) and str_input[j] == str_input[i]:
count += 1
j += 1
result += f"{count}{str_input[i]}"
i = j
print(result)
💐The End💐点点关注,收藏不迷路💐
|