面试题4 将一个char数组中的所有空格替换成%20

题目: 将一个字符串 (char数组) 中的所有空格都替换成 "%20". 这里假设数组中是有足够的空余空间的  所以不需要扩展数组

 

解题思路就是 首先判断数组中到底有多少个空格 这样就可以知道 新的数组有多长 然后反着遍历数组 从最后一个开始  将字符串中的最后一个字符  移动到新的最后一个位置  然后是倒数第二个  一旦遇到空格就将 '0', '2', '%' 三个字符分别插入新的位置 以此类推

代码如下

  public void mySolution(char[] str){
    int last = findLastChar(str);
    if(last==0){
      str = null;
      return;
    }

    int numOfSpace = countSpace(str, last);
    int newLastChar = findNewLastChar(str, numOfSpace);

    int a = last, b = newLastChar;
    while(a>=0){
      if(str[a]!=' '){
        str[b--] = str[a];
      }else{
        str[b--] = '0';
        str[b--] = '2';
        str[b--] = '%';
      }
      a--;
    }
  }


  private int findLastChar(char[] a){
    int last = 0;
    for(int i=a.length-1; i>=0; i--){
      if(a[i]==' ') continue;
      last = i;
      break;
    }
    return last;
  }


  private int countSpace(char[] a, int oldLast){
    if(oldLast==0)  return 0;

    int count = 0;
    for(int i=0; i<oldLast; i++)  if(a[i]==' ') count++;

    return count;
  }


  private int findNewLastChar(char[] a, int spaceCount){
    int last = findLastChar(a);

    if(spaceCount==0) return last;
    else  return last+2*spaceCount;
  }

此方法假设第一个字符并不是空格 如果字符串前面有若干空格 则也会将这些空格变成 "%20"

此方法中 findLastChar 运行时间是O(n) countSpace 和 findNewLastChar 运行时间都是 O(1) while 循环的运行时间是 O(n) 所以总的运行时间是 O(n)

此方法不需要额外的空间 所以时间复杂度是 O(1)

posted @ 2015-12-24 12:28  橙喵moe  阅读(1168)  评论(0编辑  收藏  举报