剑指Offer编程题(Java实现)——替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

解题思路

要求时间复杂度 O(M + N),空间复杂度 O(1)。其中 M 为行数,N 为 列数。

该二维数组中的一个数,小于它的数一定在其左边,大于它的数一定在其下边。因此,从右上角开始查找,就可以根据 target 和当前元素的大小关系来缩小查找区间,当前元素的查找区间为左下角的所有元素。

参考链接:https://www.nowcoder.com/discuss/198840?tdsourcetag=s_pcqq_aiomsg

参考实现

public boolean Find(int target, int[][] matrix) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
        return false;
    int rows = matrix.length, cols = matrix[0].length;
    int r = 0, c = cols - 1; // 从右上角开始
    while (r <= rows - 1 && c >= 0) {
        if (target == matrix[r][c])
            return true;
        else if (target > matrix[r][c])
            r++;
        else
            c--;
    }
    return false;
}

JDK实现

public class Solution {
    public String replaceSpace(StringBuffer str) {
        int index = 0;
        while((index = str.indexOf(" ",index)) != -1){
            str.replace(index, index + 1, "%20");
        }
        
        return str.toString();
    }
}

 

猜你喜欢

转载自www.cnblogs.com/MWCloud/p/11235080.html