Print all possible strings that can be made by placing spaces - GeeksforGeeks
Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them.
http://www.shuatiblog.com/blog/2015/10/07/all-string-placing-space/
==> Use StringBuilder
Given a string you need to print all possible strings that can be made by placing spaces (zero or one) in between them.
void
printPatternUtil(
char
str[],
char
buff[],
int
i,
int
j,
int
n)
{
if
(i==n)
{
buff[j] =
'\0'
;
cout << buff << endl;
return
;
}
// Either put the character
buff[j] = str[i];
printPatternUtil(str, buff, i+1, j+1, n);
// Or put a space followed by next character
buff[j] =
' '
;
buff[j+1] = str[i];
printPatternUtil(str, buff, i+1, j+2, n);
}
// This function creates buf[] to store individual output string and uses
// printPatternUtil() to print all permutations.
void
printPattern(
char
*str)
{
int
n =
strlen
(str);
// Buffer to hold the string containing spaces
char
buf[2*n];
// 2n-1 characters and 1 string terminator
// Copy the first character as it is, since it will be always
// at first position
buf[0] = str[0];
printPatternUtil(str, buf, 1, 1, n);
}
http://www.shuatiblog.com/blog/2015/10/07/all-string-placing-space/
==> Use StringBuilder
public void printAll(String input) {
if (input == null || input.length() <= 1) {
// since we insert space in-between chars, so
return;
}
int len = input.length();
// len >= 2
helper(input, len - 1);
}
private void helper(String s, int p) {
if (p == 1) {
System.out.println(s);
// no insertion
System.out.println(s.substring(0, 1) + " " + s.substring(1));
// insert at position 1
} else {
helper(s, p - 1);
helper(s.substring(0, p) + " " + s.substring(p), p - 1);
}
}
Read full article from Print all possible strings that can be made by placing spaces - GeeksforGeeks