2014-11-25 52 views
1

我正試圖在Java中實現這樣的場景。需要對字符串值進行排序,同時忽略對空字符串值的任何位置更改

我有一個ArrayList

["23","5","","","54","20","","","","0"]` 

目前,該列表是沒有排序,我想它的方式,空字符串""的位置保持排序。

這意味着空字符串不排序,其他值是。 實施例 的ArrayList

["0","5","","","20","23","","","","54"]. 

注意,空字符串(最初在位置2,3 & 6,7,8)的位置被保持之後和分類僅與非空值來實現。我使用Java,我真的很想有一些想法來開始實現這個要求。我曾嘗試谷歌,但無法找到一個開始就此。

請幫忙,

在此先感謝。

+4

發佈您嘗試過的代碼。 – theGreenCabbage 2014-11-25 09:58:18

回答

1

也許類似的東西:(貸湯姆他有用的鏈接)

String[] arr = new String[] { "23","5","","","54","20","","","","0" }; // the original array 
    boolean[] space = new boolean[arr.length]; // indicates whenever the index contains an empty space 
    String[] target = new String[arr.length]; // the reslted array 

    for (int i = 0; i < space.length; i++) // init spaces 
    { 
     space[i] = arr[i].isEmpty(); 
    } 

    Arrays.sort(arr); // sort the original array 

    int index = 0; 
    for (int i = 0; i < arr.length; i++) 
    { 
     if (arr[i].isEmpty()) continue; // just a space ignore that 
     index = i; // real values start here 
     break; 
    } 

    for (int i = 0; i < space.length; i++) 
    { 
     if (space[i] == true) 
     { 
      target[i] = ""; // restore space 
     } 
     else 
     { 
      target[i] = arr[index]; index++; 
     } 
    } 
+0

這是一個很長的代碼。你爲什麼沒有測試它?或者,如果您已經測試過,爲什麼它的語法錯誤? – Tom 2014-11-25 10:12:07

+0

謝謝..複製粘貼錯誤。我可以縮短它,但保持它乾淨和不可逾越 – ymz 2014-11-25 10:17:26

+1

「複製粘貼錯誤」?從哪裏複製?這仍然無法運行。如果您沒有安裝Java環境,請嘗試以下操作:http://ideone.com/。 – Tom 2014-11-25 10:22:09

1

也許你會想用這樣的:

import java.util.Arrays; 
import java.util.LinkedList; 
import java.util.TreeSet; 


public class StringSort { 

    public static void main(String[] args) { 
     String[] numbers = new String[] {"23","5","","","54","20","","","","0"}; 
     // Save the indices to be able to put the sorted numbers back in the array 
     LinkedList<Integer> indices = new LinkedList<>(); 
     // Keep an ordered list of parsed numbers 
     TreeSet<Integer> set = new TreeSet<>(); 
     // Skip empty entries, add non-empty to the ordered set and the indices list 
     for (int i = 0; i < numbers.length; i++) { 
      if (numbers[i].equals("")) 
       continue; 
      set.add(Integer.parseInt(numbers[i])); 
      indices.add(i); 
     } 

     // Put the ordered integers back into the array 
     for (int i : set) { 
      numbers[indices.pop()] = Integer.toString(i); 
     } 
     System.out.println(Arrays.toString(numbers)); 
    } 
} 

它運行在O(nlogn )時間,因爲排序,但這是可行的。

相關問題