替换字符串里的空格与基本字符串压缩

来源:互联网 发布:java员工管理系统 ssh 编辑:程序博客网 时间:2024/06/04 18:26

这里写图片描述
我并没用到lengh参数,首选算出有多少个空格,然后构造新的数组,主要为了解决空间问题。然后查到到空格的位置并将之后的元素都向后移动两个元素,原来的查找跳3步,如果没找到空格跳1步下标。最后就找到空格,依次插入%20即可。

public static String replaceSpace(String iniString, int length) {            // write code here         char[] charArray = iniString.toCharArray();         //首先输出有多少个空格         int count = 0;         for(int i = 0;i < charArray.length;i ++)         {            if(charArray[i] == ' ')            {                count ++;            }         }         //重新初始化数组,每多一个空格要多开辟两个空间         char[] newArray = new char[charArray.length + count * 2];         //赋值         for(int i = 0;i < charArray.length;i ++)         {             newArray[i] = charArray[i];         }         //移动并插入         for(int i = 0;i < newArray.length;)         {             if(newArray[i] == ' ')             {                 //该下表后的元素都要移动2个                 //从后向前                 for(int j = newArray.length - 1;j >= i + 2;j --)                 {                     newArray[j] = newArray[j - 2];                 }                 i += 3;             }             else             {                 i ++;             }         }         //空间已经满足条件         //准备插入         for(int i = 0;i < newArray.length;i ++)         {             if(newArray[i] == ' ')             {                 newArray[i] = '%';                 newArray[i + 1] = '2';                 newArray[i + 2] = '0';             }         }         return String.valueOf(newArray);        }

这里写图片描述

 // write code here        //转换成char数组        char[] cArray = iniString.toCharArray();        //定义一个StringBuffer用来拼接        StringBuffer sb = new StringBuffer();        //定义一个有没压缩的布尔变量,默认为没压缩        boolean isSub = false;        for (int i = 0,count = 1; i < cArray.length;) {            //先拼接            sb.append(cArray[i]);            //记录连续的数字,防止数组溢出            if(i + 1 < cArray.length)            {                for(int j = i + 1;cArray[i] == cArray[j];j ++)                {                    //满足条件则存在压缩,布尔变量为真                    isSub = true;                    count ++;                    //跳出循环                    if(j == cArray.length - 1)                    {                        break;                    }                }            }            //拼接数字,并将外层循环跳到下一个不同的字符上去            if(count != 1)            {                sb.append(count);                i += count;                count = 1;            }            else            {                //如果没有相同的,则为1                sb.append(1);                i ++;            }        }        //判断布尔并返回        return isSub?sb.toString() : iniString;
0 0
原创粉丝点击