剑指offer(题四)

来源:互联网 发布:php单选框默认选中 编辑:程序博客网 时间:2024/05/11 17:02

题意:将一个字符串中所有的空格替换成指定的字符串。
思路:先遍历字符串,计算有多少空格,再计算将该字符串中空格替换了指定字符串后,替换后的长度是多大。初始化一个长度为替换后长度的数组,设定两个游标,index1指向替换后数组的末尾,index2指向替换前字符串的末尾,从后往前遍历,若index2指定的字符为空格,则在index1指定的位置加上待替换的字符串,否则则将字符复制至index1位置。
代码:

package MianShiTi_4;public class MianShiTi_4 {    public static int countSpace(String newstring){        int count =0;        for(int i = 0; i< newstring.length() ; i++){            if(newstring.charAt(i) == ' '){                count++;            }        }        return count;    }    public static int  calLength(String newstring) {        int length = 0;        int spaceCount = 0;        spaceCount = countSpace(newstring);        length = newstring.length() + spaceCount*2;        return length;    }    public String replaceAllSpace(String newString){        String s1;        int newlength = calLength(newString);        int originalLength = newString.length();        char []tempArray = new char[newlength];        System.arraycopy(newString.toCharArray(), 0, tempArray, 0, newString.toCharArray().length);        int indexOfString = originalLength - 1;        int indexOfNewString = newlength - 1;        while (indexOfString >=0 && indexOfString != indexOfNewString) {            if(newString.charAt(indexOfString) == ' '){                tempArray[indexOfNewString--] = '0';                tempArray[indexOfNewString--] = '2';                tempArray[indexOfNewString--] = '%';            }else{                tempArray[indexOfNewString-- ] = tempArray[indexOfString];            }            indexOfString --;        }        s1 =new String(tempArray);        return s1;    }    public static void main(String[] args) {        String string = "I am ok";        MianShiTi_4 test = new MianShiTi_4();        int count1 = test.countSpace(string);        int count2 = test.calLength(string);        String s2;        s2 = test.replaceAllSpace(string);        System.out.println(s2);        //System.out.println(count1+"   "+count2);    }}
0 0
原创粉丝点击