Remove Repeat
First, the principle of de-weight
1, to sort
2, to determine whether to meet the ' two strings of the same ' condition, the same cumulative number of repetitions, and use continue to continue the next cycle
3. When the condition is not satisfied, add the string and the accumulated number to the array, and reset the accumulated value.
Second, the source code
1, a long time ago written, I will not say more.
Importjava.util.ArrayList;Importjava.util.List;//a go-to-weight algorithm, which is a little complicated to write, not optimized. Public classRemoverepeat { Public Static voidMain (string[] args) {string[] array= {"A", "a", "B", "C", "C", "D", "E", "E", "E", "F", "F", "F", "Dagds", "Dagds"}; List<String> STRs =removerepeat (array); for(String string:strs) {System.out.print (string+" "); } } Public StaticList<string>removerepeat (string[] array) {List<String> STRs =NewArraylist<string>(); for(inti = 0; i<array.length; i++) { intCount = 1; for(intj = i+1; J < Array.Length; J + +) { if(Array[i] = =Array[j]) {Count++; } if(Array[i]! = Array[j] | | j = = Array.length-1) {Strs.add (array[i]); Strs.add (String.valueof (count)); if(j!=array.length-1) {i= J-1; }Else{i=array.length-1; } Break; } } } returnSTRs; }}
2, after the optimization, in fact, only the middle of the 8 lines of code.
Importjava.util.ArrayList;Importjava.util.Arrays;Importjava.util.List; Public classRemoverepeatarray { Public Static voidMain (string[] args) {string[] Sourcearray= {"A", "B", "A", "C", "B", "D", "D", "Rsad", "B", "C", "RASDF" }; List<String> arrays =removerepeat (Sourcearray); for(inti = 0; I < arrays.size (); i++) {System.out.print (Arrays.get (i)+ " "); } } Public StaticList<string>removerepeat (string[] sourcearray) {List<String> arrays =NewArraylist<string>(); Sourcearray= Getsort (Sourcearray);//Sort , Arrays.sort (); does not support ordering of string arrays, so I wrote a simple sortSystem.out.println (arrays.tostring (sourcearray)); intCount = 1; for(inti = 0; i < sourcearray.length; i++) { //This adds a condition to prevent array subscript out of bounds exception if(I < sourcearray.length-1 && Sourcearray[i].equals (sourcearray[i + 1)]) {count++; Continue; } arrays.add (Sourcearray[i]); Arrays.add (String.valueof (count)); Count= 1; } returnarrays; } Public Staticstring[] Getsort (string[] arrays) { for(inti = 0; i < arrays.length-1; i++) { for(intj = 0; J < arrays.length-1-I; J + +) { if(Arrays[j].compareto (arrays[j + 1]) > 0) {String temp=Arrays[j]; ARRAYS[J]= Arrays[j + 1]; Arrays[j+ 1] =temp; } } } returnarrays; }}
Third, PostScript
1, there are errors please advise, thank you.
2, forwarding please indicate the source.
Go-to-weight algorithm, simple rough & optimized version