Write a function to convert a collection of strings into a single string and a function to convert it back.
Anonymous
I would use an array of integer to represent to position of the space between two strings. package com.google.interview2; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class ConvertCollToString { private static List spaces = new ArrayList(); public static String convertCollToString(Collection words){ spaces.clear(); StringBuffer sb = new StringBuffer(); for (String s : words){ sb.append(s); spaces.add(sb.length()); } return sb.toString(); } public static Collection convertStringToCollection(String s){ Collection words = new ArrayList(); int start = 0; for (Integer space : spaces){ words.add(s.substring(start, space)); start = space; } return words; } public static void main(String[] args){ Collection words = new ArrayList(); words.add("my"); words.add("name"); words.add("is"); words.add("liron"); String s = convertCollToString(words); System.out.println(s); words = convertStringToCollection(s); for (String str : words){ System.out.println(str); } } }
Check out your Company Bowl for anonymous work chats.