Recently encountered a problem: in a character array, there are letters and spaces, then you need to move all the spaces to the back, the front of the letters in sequential row together,
Solution 1: Two-layer loop, nesting ratio pair, this is more stupid, I was the interview is the use of this, the time complexity of N-side.
Solution 2: Using two cursors, starting with the first element, if a letter is encountered, then two cursors move at the same time, if a space is encountered, where the first cursor continues to move, the second cursor stops moving, swaps the element, and then moves the second cursor with a time complexity of N.
The time code below
/** * Move Space: * A character array, inside the letters and spaces, you need to move all the space behind the array, the characters in order to move to the front * * @create 2018-04-03 22:54 **/public class Blankfilter { /** * Two layers of nested loops, time complexity: N-party * @param arr */public static void Forfilter (char[] arr) {for (int i = 0; i < arr.length; i++) {if (arr[i] = = ") {//Find space for (int j = i; J < Arr.length; J + +) {if ( ARR[J]! = ") {//from after finding non-whitespace char temp = arr[i]; Arr[i] = Arr[j]; ARR[J] = temp; }}}}}/** * Two subscripts, time complexity N * @param arr */public static void T Woindexfilter (char[] arr) {int i = 0, j = 0; for (; i < arr.length; i++) {//I subscript always move forward if (arr[i]! = "&& J < Arr.length) {//If a non-space is encountered, then enter at this time, in the most After J moves backward one position if (i! = j) {//If I and J are equivalent, then no spaces are encountered in front of it, because if the case is non-whitespace, two subscript is moving char tmp = ARR [i]; Arr[i] = Arr[j]; ARR[J] = tmp; } j++;//i and J subscript all move forward}}} public static void Main (string[] args) {char[] A = {' A ', ' ', ' ', ' B ', ' ', ' C '}; Solution One: The most stupid way, two layers of nested loops: Time complexity N-side//Forfilter (a); Twoindexfilter (a); for (char ch:a) {System.out.println (ch + ","); } }}
Move spaces to the last Java implementation in a character array