Skip to main content
Code Review

Return to Revisions

2 of 4
added 5 characters in body
janos
  • 113k
  • 15
  • 154
  • 396

new StringBuilder is really needed?

Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;

frontTimes("Chocolate", 2) → "ChoCho"
frontTimes("Chocolate", 3) → "ChoChoCho"
frontTimes("Abc", 3) → "AbcAbcAbc"

I've solved above problem using following code but I'm using a new StringBuilder to store intermediate string result, does it really needed can I optimize and remove for loop in else?

public String frontTimes(String str, int n) {
 
 StringBuilder sb = new StringBuilder(str);
 StringBuilder newsb = new StringBuilder();
 
 if(sb.length() >= 3)
 {
 for(int i = 0; i < n; i++)
 {
 newsb.append(sb.substring(0,3));
 }
 
 return newsb.toString(); 
 }
 else
 {
 for(int i = 0; i < n; i++)
 {
 newsb.append(sb.toString());
 }
 
 return newsb.toString();
 
 }
 
 }
lang-java

AltStyle によって変換されたページ (->オリジナル) /