I need to replace non-digit characters from an array of String and return a String with digits separated by coma, actually, I made it but don't like it.
The first thing I made, was added values from the String array to the String.
Then I replaced non-digit characters from a String.
After that, I added digit values to an int array and sorted it.
Then I added all this stuff to an array of strings and separated values with commas, after that I returned it.
I would be glad for advice, thanks for attention.
import java.util.Arrays;
class Test {
private static String sortedStringOfNumber(String[] string) {
StringBuilder temp = new StringBuilder();
for (String s: string) {
temp.append(s);
}
String numberOnly = temp.toString().replaceAll("[^0-9]", "");
int[] numbers = new int[numberOnly.length()];
for (int i = 0; i < numberOnly.length(); i ) {
numbers[i] = numberOnly.charAt(i) - '0';
}
Arrays.sort(numbers);
String[] result = new String[numbers.length];
for (int i = 0; i < numbers.length; i ) {
result[i] = String.valueOf(numbers[i]);
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.length; i ) {
sb.append(result[i].toString());
if (i != result.length - 1)
sb.append(", ");
}
return sb.toString();
}
public static void main(String[] args) {
String[] arrayStringData = new String[] { "1", "ab3c", "level", null, "java2s.com", "asdf 456", "Br0C0de" };
//Should be "0, 0, 1, 2, 3, 4, 5, 6"
System.out.println("Sorted string of numbers ->\t" sortedStringOfNumber(arrayStringData));
}
}
CodePudding user response:
Your solution would run in O(n*log n) mainly due to Arrays.sort.
Use a simple counting sort. This would give you a runtime of O(n).
Look at the string and ignore all other non-digits.