1. 程式人生 > >去重算法,簡單粗暴&優化版

去重算法,簡單粗暴&優化版

一個 dag 代碼 text 下標 數組 repeat 次數 style

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、轉發請註明出處。

去重算法,簡單粗暴&優化版