我想知道如何在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)标记输入字符串,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) 中完成,并使用排序操作使代码更清晰。