去重算法,简单粗暴&优化版
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、转发请注明出处。