M面经Prepare: Delete Words Starting With One Character

 给定一个char array, 这个array是一个句子,然后给定一个字母,把这个array里面带有这个字母开头的单次删掉,操作是要求in place. 

检测   array[i]==' ' && i<array.length-1 && array[i+1]==target,这种情况,设置j从i+1开始直到找到下一个‘ ’或者到达末尾,然后中间的全部删掉,i从j开始

特别要注意第一个char是target的情况

 1 package DeleteWordsStartByCertainChar;
 2 
 3 import java.util.*;
 4 
 5 public class Solution {
 6     public char[] modify(char[] array, char tar) {
 7         if (array==null || array.length==0) return new char[0];
 8         int index=0;
 9         int i=0;
10         for (; i<array.length; i++) {
11             if (i==0 && array[i]==tar || array[i]==' ' && i<array.length-1 && array[i+1]==tar) {
12                 int j = i+1;
13                 while (j<array.length && array[j]!=' ') j++;
14                 i = j;
15                 i--;
16             }
17             else array[index++] = array[i];
18         }
19         char[] res = Arrays.copyOf(array, index);
20         return res;
21     }
22     
23 
24     /**
25      * @param args
26      */
27     public static void main(String[] args) {
28         // TODO Auto-generated method stub
29         Solution sol = new Solution();
30         char[] array = "ab big ball bis brunning b ".toCharArray();
31         char[] res = sol.modify(array, 'b');
32         System.out.println(res);
33     }
34 
35 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/5191627.html