Remove leading/trailing/ and duplicate space with one remaining
Problem:
Remove leading/trailing/ and duplicate space with one remaining
//input "_ _ _ you_ _ _get_ _ _ offer_ _ _" , output "you_get_offer"
Solution:
s1: keep the space after the word;
public String removeSpace(String str){
if(str == null || str.length == 0) return null;
char[] array = str.toCharArray();
int slow = 0;
for(int fast = 0; fast < array.length; fast++){
if(array[fast] != ' ' || fast != 0 && array[fast - 1] != ' '){
array[slow++] = array[fast];
}
}
if(slow == 0) return '';
return array[slow-1] ==' ' ? new String(array, 0, slow-1) : new String(array, 0, slow);
}
Last updated
Was this helpful?