码迷,mamicode.com
首页 > 其他好文 > 详细

LF.281.Remove Spaces

时间:2018-04-05 13:28:19      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:ase   分享图片   move   blog   keep   .com   src   return   com   

Given a string, remove all leading/trailing/duplicated empty spaces.

Assumptions:

The given string is not null.
Examples:

“ a” --> “a”
“ I love MTV ” --> “I love MTV”

 1 public String removeSpaces(String input) {
 2         // Write your solution here
 3         //corner case
 4         if (input.isEmpty()){
 5             return input ;
 6         }
 7         /*
 8         return [0, i) j is the counter
 9         * case 1: not space: input[i++] = input[j++]
10         * case 2: if space
11         *         2.1: leading space: skip
12         *         i = 0
13         *         2.2: duplicate space: keep the first space
14         *         j != j-1 : j一定是SPACE, J-1 如果不是的话,把当前的SPACE 给I 吃
15         *         2.3: trailing space : remove
16         *         j to the end, and i = "", i--
17         * */
18         int slow = 0, fast = 0;
19         char[] chars = input.toCharArray();
20         while (fast < chars.length){
21             if (chars[fast] !=‘ ‘ ){
22                 chars[slow++] = chars[fast++] ;
23             } else{
24                 //非开头, 中间没连续_ 末尾可能进去一个 _
25                 if (slow>0 && chars[fast] != chars[fast-1]){
26                     chars[slow++] = chars[fast++] ;
27                 } else{
28                     fast++ ;
29                 }
30             }
31         }
32         //post-processing: it is possible we still have one trailing ‘ ‘
33         if (slow>0 && chars[slow-1] == ‘ ‘){
34             return new String(chars, 0, slow-1) ;
35         }
36         return new String(chars, 0, slow) ;
37     }

 

技术分享图片

技术分享图片

 

LF.281.Remove Spaces

标签:ase   分享图片   move   blog   keep   .com   src   return   com   

原文地址:https://www.cnblogs.com/davidnyc/p/8721937.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!