-3

It is an interview question. The input is an ArrayList. My first idea is to convert it into a 2D matrix and then combine each column, but it seem like not the right answer. Is there any other way to solve this? Thanks.

Input

"abc", 
"bef", 
"g"

Expected Output (first column, abg, then the second column, be and finally the third column, cf):

"abgbecf"
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
RubyA
  • 1
  • Specifically looking at the second answer: `String listString = String.join("", list);` https://stackoverflow.com/a/23183963/8534008 – GBlodgett Nov 13 '18 at 19:30
  • input order and output order are different, or order is not mandatory ? – Ryuzaki L Nov 13 '18 at 19:35
  • 1
    loop from 0 to max(lengths of the words). At each iteration, loop through each word and append the nth character (if it exists) of the current word to a StringBuilder. Done. – JB Nizet Nov 13 '18 at 19:35

3 Answers3

0

Something like this would work:

StringBuilder sb = new StringBuilder()
int max = 0;
for(String str : arrList){
    if(str.length > max) { 
        max = str.length;
    }
}
for(int i = 0; i < max; i++){
    for(String str : arrList){
        if(str.length > i){
            sb.append(str.charAt(i));
        }
    }
}
return sb.toString();
The Zach Man
  • 738
  • 5
  • 15
0

I think I would simply loop through the list pulling the next character out of the original strings and adding it to the new combined string, until the last letter of the longest string was added.

boolean keepGoing = true;
int index = 0;
StringBuilder result = new StringBuilder();
while(keepGoing) {
    keepGoing = false;
    for(int i=0; i < stringList.size(); i++) {
        if(stringList.get(i).length() > index) {
            result.append(stringList.get(i).charAt(index));
            keepGoing = true;
        }
    }
    index++;
}
System.out.println("result: " + result);

There are probably more elegant solutions, but this is what I would start with and then refine as needed.

Blair
  • 76
  • 5
-1

An easy way would be to use a StringBuilder:

StringBuilder sb = new StringBuilder()
for(String str : arrList){
    sb.append(str)
}
return sb.toString()
Turtalicious
  • 430
  • 2
  • 5