如何知道字符串中的数字是否按Java排序

时间:2015-04-13 13:47:46

标签: java string

我想知道如何在java中实现一个布尔方法,它告诉我字符串中的数字是否按升序排序。

例如,假设我有这个字符串。

ZALAME 2 3
PECASH 1 3 6
PATEAN 3 4
RAMION 3 6

我需要实现一些方法,如:

public boolean areOrdered(String theText){
//Lets say I do separate each line of the String into a String array.
String[] lines = theText.split(System.getProperty("line.separator"));
//Now I could do some FOR loop in order to check each individual string.
for(int i = 0; i<lines.length; i++){
//Here is where I check the numbers, taking appart the letters. How could I do it?
if (condition that only applies if numbers are not ordered) return false;
}
return true;
}

原则应该是:

    If I check this one:
    ZALAME 2 3
    PECASH 1 3 6
    PATEAN 3 4
    RAMION 3 6
It would return **true** BUT if I check this one:
    ZALAME 3 2
    PECASH 1 3 6
    PATEAN 3 4
    RAMION 3 6
It would return **false**

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您应该:1)标记输入字符串,2)从标记中收集数字,3)将排序的数字列表与初始值进行比较

String input = "PECASH 1 3 6";
boolean acsending = isAcsending(input); 

...

public static isAcsending(String input) {

   String[] splitted = input.split("\\s+");  // tokenize string
   List<Integer> ints = new ArrayList<>(); 
   for (String s : splitted) {  
     try {
         ints.add(Integer.parseInt(s));         // try to parse each token 
     } catch (RuntimeException ignored) { }
   }
   List<Integer> sorted = new ArrayList<>(ints);
   Collections.sort(sorted);
   return ints.equals(sorted);               // compare
}

我知道这可以在O(n)而不是O(nlogn)中完成,并使用排序操作来使代码更清晰。

相关问题