URLify a given String - replace spaces with %20 I have written a code to replace all spaces in a String with %20.
Input: &quot;Mr John Smith &quot;
Output: &quot;Mr%20John%20Smith&quot;

My logic:
public class URLify {
    public static void main(String[] args) {
        String str = &quot;Mr John Smith  &quot;;
        str = str.stripTrailing();
        char[] ch = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for(char c : ch) {
            if(c != ' ')
                sb.append(c);
            else {
                sb.append(&quot;%20&quot;);
            }
        }
        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 &lt; 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 &gt; MAX)
        return str;
    int index = new_length - 1;
    char[] old_str = str;
    str = new char[new_length];
    for (int j = i - 1; j &gt;= 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 () however, can someone please suggest which solution is a better one especially if asked in an interview? Thanks!
Review
Welcome to Code Review. There are some suggestions as follows.
Consider to use replaceAll
The operation you performed is what String.replaceAll do, you can use replaceAll directly instead of String.toCharArray(), whitespace comparison, and sb.append things.
Create a method URLify
In order to improve usability, it is better to create a method URLify to perform this specific operation.
Summary
Combine all the things:
public class URLify {
    
    public static String URLify(String input){
        return input.stripTrailing().replaceAll(&quot; &quot;,&quot;%20&quot;);
    }
    
    public static void main(String[] args) {
        String str = &quot;Mr John Smith  &quot;;
        System.out.println(URLify(str));
    }
}