【剑指offer】替换空格

问题描述

【剑指offer】替换空格_第1张图片

暴力法:

【剑指offer】替换空格_第2张图片

package cn.jnu.ma02;

public class Solution {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s="we are happy";
		StringBuffer str = new StringBuffer(s);
		System.out.println(s);
		System.out.println(replaceSpace(str));
	}
    public static String replaceSpace(StringBuffer str) {
        if (str == null || str.length() == 0) {
            return str.toString();
        }
        StringBuilder sb = new StringBuilder();
        int len = str.length();
        for (int i = 0; i < len; ++i) {
            char ch = str.charAt(i);
            sb.append(ch == ' ' ? "%20" : ch);
        }
        return sb.toString();
    }
}

思路二:双指针法

【剑指offer】替换空格_第3张图片

package cn.jnu.ma02;

public class Solution2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s="we are happy";
		StringBuffer str = new StringBuffer(s);
		System.out.println(s);
		System.out.println(replaceSpace(str));
	}

	public static String replaceSpace(StringBuffer str){
        if (str == null || str.length() == 0) {
            return str.toString();
        }
        
        int len = str.length();
        for (int i = 0; i < len; ++i) {
            if (str.charAt(i) == ' ') {
                // append 两个空格
                str.append("  ");
            }
        }

        // p 指向原字符串末尾
        int p = len - 1;

        // q 指向现字符串末尾
        int q = str.length() - 1;

        while (p >= 0) {
            char ch = str.charAt(p--);
            if (ch == ' ') {
                str.setCharAt(q--, '0');
                str.setCharAt(q--, '2');
                str.setCharAt(q--, '%');
            } else {
                str.setCharAt(q--, ch);
            }
        }
        return str.toString();
	}	
}

你可能感兴趣的:(剑指offer,【剑指offer】---随记)