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:
算法:
STEP 1: Declaring a recursive function pairStar with parameters (char arr[], int start)
步骤1:使用参数(char arr [],int开始)声明一个递归函数pairStar
STEP 2: Base Case: if(arr[start] == '\0') return;
步骤2:基本情况: if(arr [start] =='\ 0')return;
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。
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
c++ 字符串配对int型