zoukankan      html  css  js  c++  java
  • 剑指offer2 替换空格

    请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当

    字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

    package z_jzoffer.jz2;
    
    import java.util.Stack;
    
    /**
     * @author houChen
     * @date 2020/8/17 20:02
     * @Description:
     */
    public class Solution2 {
        public static void main(String[] args) {
            StringBuffer str = new StringBuffer();
            str.append("We Are Happy");
            Solution2 solution2 = new Solution2();
            String s = solution2.replaceSpace(str);
            System.out.println(s);
        }
    
        public String replaceSpace(StringBuffer str) {
            //将空格在字符串中的开始位置 保存在一个int[]
            int[] arr = new int[100];
            int count=0;
    
            for(int i=0;i<str.length();i++){
                if(str.charAt(i)==' '){
                    arr[count++]=i;
                }
            }
    
            for(int j= count-1;j>=0;j--){
                str.replace(arr[j],arr[j]+1,"%20");
            }
            return str.toString();
        }
    
        /*public String replaceSpace(StringBuffer str) {
            //将空格在字符串中的开始位置 保存在一个int[]
            Stack<Integer> s = new Stack<Integer>();
    
            for(int i=0;i<str.length();i++){
                if(str.charAt(i)==' '){
                    s.push(i);
                }
            }
    
            while(!s.isEmpty()){
                str.replace(s.peek(),s.peek()+1,"%20");
                s.pop();
            }
            return str.toString();
        }*/
    }
  • 相关阅读:
    团队作业4_项目冲刺
    Scrum冲刺_Day07
    Scrum冲刺_Day06
    Srcum冲刺_Day05
    Day1-7【Scrum 冲刺博客集合】
    团队作业6——事后诸葛亮分析
    团队作业6——Alpha阶段项目复审
    团队作业5——测试与发布(Alpha版本)
    Day7 【Scrum 冲刺博客】
    Day6【Scrum 冲刺博客】
  • 原文地址:https://www.cnblogs.com/houchen/p/13532643.html
Copyright © 2011-2022 走看看