[LeetCode-Simple question] Sword pointing at Offer 05. Replace spaces

topic

Insert image description here

Method 1: Conventional approach:

class Solution {
    
    
    public String replaceSpace(String s) {
    
    
        int len = s.length() ;
        StringBuffer str = new StringBuffer();
        for(int i = 0 ; i < len ; i++){
    
    
            if(s.charAt(i) == ' ') str.append("%20");//遇到空格就在尾部拼接%20
            else str.append(s.charAt(i));//遇到字符就在尾部正常拼接字符
        }
        return str.toString();
    }
}

Method 2: Double pointer approach

Insert image description here

class Solution {
    
    
    public String replaceSpace(String s) {
    
    
        int len = s.length() ;
        StringBuffer str = new StringBuffer(s);
         if( len == 0  ) return "";
         for(int i = 0 ; i< len ; i++)
             if(s.charAt(i)==' ') str.append("  ");//扩充空间,空格数量2倍
        String string = str.toString();
        char[] strs = string.toCharArray();
        int left = s.length()-1;
        int right = str.length()-1;
        while(left >= 0 ){
    
    
            if(str.charAt(left) == ' '){
    
    
                strs[right--] = '0';
                strs[right--] = '2';
                strs[right] = '%';
            }else strs[right] = strs[left];
            right--;
            left--;
        }
        return new String(strs);
    }
}

Guess you like

Origin blog.csdn.net/weixin_45618869/article/details/132887530