c++ 字符串配对int型_配对情况:C ++程序在字符串的两个相同字符之间输入“ *”...

本文介绍了一种C++算法,用于在字符串中相邻的相同字符间插入星号。通过递归方法,该算法能够有效地处理字符串,并在每对重复字符间添加分隔符。

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

c++ 字符串配对int型

Given a string, compute recursively a new string where identical chars that are adjacent in the original string are separated from each other by a "*".

给定一个字符串,请递归计算一个新字符串,其中原始字符串中相邻的相同字符由“ *”分隔

Sample Input 1: "hello"

示例输入1: “ hello”

Sample Output 1: "hel*lo"

样本输出1: “ hel * lo”

Sample Input 2: "xxyy"

样本输入2: “ xxyy”

Sample Output 2: "x*xy*y"

样本输出2: “ x * xy * y”

Sample Input 3: "aaaa"

样本输入3: “ aaaa”

Sample Output 3: "a*a*a*a"

样本输出3: “ a * a * a * a”

Explanation:

说明:

In this question, we have to add a star between any pair of same letters. This could be easily achieved using recursion. When the start index is equal to (start + 1) index, we will shift all the letters from (start + 1) by 1 on the right side and on (start + 1), we will add a star.

在这个问题中,我们必须在任何一对相同的字母之间加一个星号 。 使用递归可以轻松实现。 当开始索引等于( 开始+ 1 )索引时,我们将在( 开始+ 1 )的右侧将所有字母从( 开始+ 1 )移位1,然后在( 开始+ 1 )上移位,我们将添加一个星号。

Algorithm:

算法:

  1. STEP 1: Declaring a recursive function pairStar with parameters (char arr[], int start)

    步骤1:使用参数(char arr [],int开始)声明一个递归函数pairStar

  2. STEP 2: Base Case: if(arr[start] == '\0') return;

    步骤2:基本情况: if(arr [start] =='\ 0')return;

  3. STEP 3: if(start == start +1)

    步骤3: if(start == start +1)

    Shift all the letters from

    将所有字母从

    start+1 to right side by 1.

    从1开始右移+1。

  4. STEP 4: Enter '*' at (start +1) in arr.

    步骤4:在arr中的(开始+1)输入'*'

Example:

例:

    Input = "aaa"
    First Traversal: "aa*a"
    Second Traversal: "a*a*a"


C++ program:

C ++程序:

#include <iostream>
using namespace std;

//Function To find length
int length(char arr[]){
	int len = 0;
	for(int i =0;arr[i]!='\0';i++){
		len++;
	}
	return len;
}

//Recursive Function
void pairStar(char arr[],int start){
	//Base Case: Reached End Of String
	if(arr[start]=='\0'){
		return;
	}   
	//Recursive Call 
	pairStar(arr,start+1);
	if(arr[start] == arr[start+1]){
		int l = length(arr);
		//Extending the string
		arr[l+1] = '\0';
		int i;
		//To shift the letters by 1
		for(i = l-1;i>=start +1;i--){
			arr[i+1] = arr [i];
		}
		//Entering * in between
		arr[start+1] = '*';
	}
}

//Main
int main(){
	char input[50];
	cout<<"Enter Input"<<endl;
	cin>> input;

	pairStar(input,0);  //Calling the function

	cout<<"Modified Output"<<endl;
	cout<<input<<endl;

	return 0;
}

Output

输出量

Enter Input
hello
Modified Output
hel*lo


翻译自: https://www.includehelp.com/cpp-programs/pair-case-program-to-enter-asterisk-between-two-identical-characters-in-a-string.aspx

c++ 字符串配对int型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值