Skip to main content
Code Review

Return to Question

edited tags
Link
pacmaninbw
  • 26.1k
  • 13
  • 47
  • 114
Source Link

URLify a given String - replace spaces with %20

I have written a code to replace all spaces in a String with %20.

Input: "Mr John Smith "
Output: "Mr%20John%20Smith"

My logic:

public class URLify {
 public static void main(String[] args) {
 String str = "Mr John Smith ";
 str = str.stripTrailing();
 char[] ch = str.toCharArray();
 StringBuilder sb = new StringBuilder();
 for(char c : ch) {
 if(c != ' ')
 sb.append(c);
 else {
 sb.append("%20");
 }
 }
 System.out.println(sb.toString());
 }
}

The given solution:

static int MAX = 1000; 
static char[] replaceSpaces(char str[]) {
 int space_count = 0, i = 0;
 for (i = 0; i < str.length; i++)
 if (str[i] == ' ')
 space_count++;
 while (str[i - 1] == ' ') {
 space_count--;
 i--;
 }
 int new_length = i + space_count * 2;
 if (new_length > MAX)
 return str;
 int index = new_length - 1;
 char[] old_str = str;
 str = new char[new_length];
 for (int j = i - 1; j >= 0; j--) {
 if (old_str[j] == ' ') {
 str[index] = '0';
 str[index - 1] = '2';
 str[index - 2] = '%';
 index = index - 3;
 }
 else {
 str[index] = old_str[j];
 index--;
 }
 }
 return str;
}

Both work correctly with a linear time complexity of O(n) however, can someone please suggest which solution is a better one especially if asked in an interview? Thanks!

lang-java

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