標籤:異常 .so size sys array tar ali valueof main
Remove Repeat
一、去重原理
1、進行排序
2、判斷是否滿足 ‘兩個字串相同‘ 的條件,相同則累加重複次數,並使用continue繼續下一次迴圈
3、當條件不滿足時,將該字串和累計數加入數組中,並重設累計值。
二、源碼
1、很久之前寫的,我就不多說了。
import java.util.ArrayList;import java.util.List;//一個去重的演算法,寫的有點複雜,沒有最佳化過public class RemoveRepeat { public static void main(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 static List<String> removeRepeat(String[] array) { List<String> strs = new ArrayList<String>(); for(int i = 0; i<array.length; i++) { int count = 1; for(int j = 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; } } } return strs; }}
2、最佳化後的,其實就只有中間的8行代碼。
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class RemoveRepeatArray { public static void main(String[] args) { String[] sourceArray = { "a", "b", "a", "c", "b", "d", "d", "rsad", "b", "c", "rasdf" }; List<String> arrays = removeRepeat(sourceArray); for (int i = 0; i < arrays.size(); i++) { System.out.print(arrays.get(i) + " "); } } public static List<String> removeRepeat(String[] sourceArray) { List<String> arrays = new ArrayList<String>(); sourceArray = getSort(sourceArray); // 排序, Arrays.sort();不支援對字串數組進行排序,所以自己寫了個簡單的排序 System.out.println(Arrays.toString(sourceArray)); int count = 1; for (int i = 0; i < sourceArray.length; i++) { //這裡多加了一個條件,防止數組下標越界異常 if (i < sourceArray.length - 1 && sourceArray[i].equals(sourceArray[i + 1])) { count++; continue; } arrays.add(sourceArray[i]); arrays.add(String.valueOf(count)); count = 1; } return arrays; } public static String[] getSort(String[] arrays) { for (int i = 0; i < arrays.length - 1; i++) { for (int j = 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; } } } return arrays; }}
三、後記
1、有錯誤請指教,謝謝。
2、轉寄請註明出處。
去重演算法,簡單粗暴&最佳化版