public static StringBuilder getLine(String... words) {
ArrayList<String> strings = new ArrayList<>();
if(words.length==0)
return new StringBuilder();
for(String s:words)
strings.add(s);
ArrayList<StringBuilder> permutedList= new ArrayList<>();
permute(strings,permutedList,0,strings.size()-1); // having the permuteList in permute method reduce lots of problem
StringBuilder sb1= checkBestFit(permutedList);
return sb1;
}
//this is quite simple method and but hard to understand
public static void permute(ArrayList<String> strings, ArrayList<StringBuilder> permutedList,int l, int r) {
if (r == l) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strings.size(); i++) {
if (i == strings.size() - 1)
sb = sb.append(strings.get(i));
else sb = sb.append(strings.get(i) + " ");
}
permutedList.add(sb);
} else {
for (int i = l; i <= r; i++) {
swap(strings, l, i);
permute(strings, permutedList,l + 1, r);
swap(strings, l, i);
}
}
}
i believe my checkBestFit(permuteList) - another waste of memory.
please if any one can improve the method which will pass i would love to hear.
public static StringBuilder checkBestFit(ArrayList<StringBuilder> list) {
StringBuilder longSB = new StringBuilder();
int maxCount = 0;
int i, index = 0;
//list contains all permutation as sb
//each sb tested for longest string
for (StringBuilder sb : list)
{
String line = sb.toString();
int count = 0;
String[] s = line.split(" "); //sb split into strings
if(s.length==0)
return new StringBuilder();
if(s.length==1)
return new StringBuilder(s[0]);
for (i = 0; i < s.length - 1; i++) {
if (s[i].toLowerCase().charAt(s[i].length() - 1) == s[i + 1].toLowerCase().charAt(0)) {
count++;
} else {
if (count > maxCount) {
maxCount = count;
count = 0;
longSB = sb;
index = i;
}
}
} //loop for each sb testing for longest string
if (count > maxCount) {
maxCount = count;
count = 0;
longSB = sb;
index = i;
}
}
StringBuilder longSB2;
longSB2 = longestStringBuilder(longSB, index- maxCount, index);
return longSB2;
I think this is badly written code but passed. i tried to do space efficient way but it wont pass.
Under discussion
Comments
- Popular
- New
- Old
You must be signed in to leave a comment
This page doesn't have any comments yet