Problem Description:
Problem Analysis:
Solution One: Set the double pointer, start,end; when data[start]= ' 1 ', data[end]= ' 0 ', indicates the need to exchange, the number of times plus 1; otherwise data[end]= ' 1 ' will move the end pointer forward; Data[start]= ' 0 ' Moves the start pointer back;
The algorithm only needs to traverse once
Solution Two: First to calculate the number of characters in the array of 0 zero, and then calculate the number of the first zero character 1, that is, to exchange to the back of the character (only need to traverse to zero characters);
Code:
Solution One:
Import Java.util.scanner;public class Main1 {public static void main (string[] args) {Scanner in = new Scanner (system.in); /record How many sets of data int data_length = In.nextint ();//First layer loop for (int i = 0; i < data_length; i++) {String str = in.next (); char[] Cha rs = Str.tochararray (); int start = 0;int end = Chars.length-1;int result = 0;while (Start < end) {if (chars[start] = = ' 1 ' && chars[end] = = ' 0 ') {++result;start ++;end--;} else {if (chars[end] = = ' 1 ') {end--;} if (chars[start] = = ' 0 ') {start + +;}}} SYSTEM.OUT.PRINTLN (result);}}}
Solution Two: Import Java.util.scanner;public class Main1 {public static void main (String args[]) {Scanner in = new Scanner (system.i n); int n = In.nextint (); while (n--! = 0) {int zero = 0, swap = 0; String str = In.next (); for (int i = 0; i < str.length (); i++) if (Str.charat (i) = = ' 0 ') zero++;for (int i = 0; i < Zer O i++) if (Str.charat (i) = = ' 1 ') swap++; SYSTEM.OUT.PRINTLN (Swap);}}}
Baidu written test-01 number of exchanges for sequential sequencing