2014-11-25 51 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 )时间,因为排序,但这是可行的。

相关问题