Sword finger Offer question 5 (Java version): replace space in string

Keywords: Programming

Reference from: Sword finger Offer - typical programming questions of famous enterprise interviewers

Title: replace space in string
Please implement a function to replace each space in the string with "% 20". For example, enter "We are happy.",
Then output "We%20are%20happy.".

Main ideas: 1. First calculate the number of spaces in the string, and then get the length of the new string (original length + number of spaces * 2). 2. Start traversing forward from the end of the string. If a space is encountered, replace the space with "% 20". Otherwise, keep the original character.

Key: the length of the new string; generally, operations such as modification and deletion are traversed from the beginning.

Time complexity: O (string length)

public class ReplaceSpace
{
    public static void main(String[] args)
    {
        String str = "hello world";
        String result = replaceSpace(str);
        System.out.println(result);
    }

    private static String replaceSpace(String str)
    {
        if (str == null || str.length() == 0) return "";
        char[] chars = str.toCharArray();
        int spaceCount = getSpaceCount(chars);

        int originalLength = chars.length;
        //New string final length
        int finalLength = originalLength + 2 * spaceCount;  
        char[] result = new char[finalLength];
        //Traverse from the back
        for (int i = originalLength - 1; i >= 0; i--)
        {
            char currentChar = chars[i];
            //Replace blank space
            if (currentChar == ' ')
            {
                result[--finalLength] = '0';
                result[--finalLength] = '2';
                result[--finalLength] = '%';
            } else
            {
                result[--finalLength] = currentChar;
            }
        }
        return String.valueOf(result);
    }

    private static int getSpaceCount(char[] chars)
    {
        int spaceCount = 0;
        for (int i = 0; i < chars.length; i++)
        {
            if (chars[i] == ' ')
                spaceCount++;
        }
        return spaceCount;
    }
}

Posted by feri_soft on Tue, 31 Mar 2020 07:15:50 -0700