Learn Algorithms with Me Series 4---Replace Spaces

1. Topic description

Please implement a function to replace spaces in a string with "%20". For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.

2. Algorithm analysis

To implement this function in java, you can directly use the replace class function. However, from the perspective of the algorithm, we can first traverse and count the number of spaces in the string, assuming n, the length of the string after replacing the spaces increases on the basis of the original length 2n. Therefore, the length of the new string is determined, traverse the original string from back to front, and replace the corresponding character with %20 when encountering a space, which is not a copy of the space as it is.

3. Code example

  public String replaceSpace(StringBuffer str)
  {
    if(null == str)
    {
        return "";
    }

    int len = str.length();
    int count = 0;
    
    for (int i = 0; i < len; i++) {
        if(str.charAt(i) == ' ')
        {
            count++;
        }
    }
    
    int newLen = len + 2*count;
    int index = newLen - 1;
    char[] newChar = new char[newLen];
    
    while(len > 0)
    {
        if(str.charAt(len - 1) == ' ')
        {
            newChar[index--] = '0';
            newChar[index--] = '2';
            newChar[index--] = '%';
        }
        else
        {
            newChar[index--] = str.charAt(len - 1);
        }
        
        len--;
    }
    
    return String.valueOf(newChar);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325722161&siteId=291194637