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

Remove Repeatjava

 

1、去重原理算法

  一、進行排序數組

  二、判斷是否知足 '兩個字符串相同' 的條件,相同則累加劇複次數,並使用continue繼續下一次循環優化

  三、當條件不知足時,將該字符串和累計數加入數組中,並重置累計值。spa

2、源碼code

  一、好久以前寫的,我就很少說了。blog

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;
    }
}

  二、優化後的,其實就只有中間的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;
    }

}

 

3、後記rem

  一、有錯誤請指教,謝謝。字符串

  二、轉發請註明出處。

相關文章
相關標籤/搜索