TATA Consultancy Services Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
public class Spaces {
public List<String> getSpaces(String initial){
String[] chars = initial.split("");
List<String> charList = Arrays.asList(chars);
List<String> pals = new ArrayList<String>();
getCombinaciones(charList.get(1), charList, pals, 2);
return pals;
}
private void getCombinaciones(String curString, List<String> charList, List<String> pals, int i) {
if(i >= charList.size()){
pals.add(curString);
}else{
getCombinaciones(curString + "_" + charList.get(i), charList, pals, i+1);
getCombinaciones(curString + "" + charList.get(i), charList, pals, i+1);
}
}
public static void main(String[] args) {
Spaces program = new Spaces();
List<String> comb = program.getSpaces("abcd");
for (String string : comb) {
System.out.println(string);
}
}
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <bitset>
using namespace std;
string insert_spaces(string x, string y){
int i;
string result;
for(i=0;i<x.length();i++){
result += x[i];
if(y[i]!='0'){
result += "_";
}
}
return result;
}
int main(){
int i;
string bitcode;
for(i=0;i<8;i++){
bitset<3> x(i);
bitcode = x.to_string();
bitcode += '0';
cout << insert_spaces("abcd",bitcode) << endl;
}
}
it returns all the string combinations in form of array.
public static string[] string_combinations(string s)
{
//points to main array index
int index = 0;
//Create an array length of n(n+1)/2
string[] combiArray = new string[(s.Length * (s.Length + 1))/2];
combiArray[index++] = s;
for (int i = 1; i < s.Length; i++)
{
//recursive call on remaining string
//eg: if s = abcd and i = 1 recursive call of (bcd)
//i = 2 recursive call of (cd)
//i = 3 recursive call of (d)
string[] subCombinations = string_combinations(s.Substring(i));
foreach (string item in subCombinations)
{
if(item != null)
combiArray[index++] = s.Substring(0,i) + "_" + item;
}
}
return combiArray;
}
- AndrewRadkovich August 04, 2014