Java string replacement sort instance
- 2020-04-01 02:49:14
- OfStack
import java.util.LinkedList;
public class OJ {
public OJ() {
super();
}
public static int getSortNum(final String input, final StringBuilder output) {
if(input.length()<=0 || input.length() > 1000){
return -1;
}
String[] nums = input.split("5");
int len = nums.length;
LinkedList<Integer> sorted = new LinkedList<Integer>();
int j = 0;
for (int i = 0; i < len; i++) {
int temp = 0;
int k = j;
if (!nums[i].equals("")) {
try {
temp = Integer.valueOf(nums[i]);
if(temp > 100000000){
return -1;
}
if (sorted.isEmpty()) {
sorted.addFirst(temp);
j++;
} else {
while (k > 0 && (temp > sorted.get(k - 1))) {
k--;
}
sorted.add(k, temp);
j++;
}
} catch (Exception ex) {
return -1;
}
}
}
for (int i = 0; i < sorted.size() - 1; i++) {
output.append(sorted.get(i) + " ");
}
output.append(sorted.getLast());
output.trimToSize();
return 0;
}
}
Test case:
import junit.framework.Assert;
import junit.framework.TestCase;
public class OJTest extends TestCase
{
public void testCase01()
{
//Write the test case here
final StringBuilder output = new StringBuilder();
Assert.assertTrue(-1 == OJ.getSortNum("1234543 215555", output));
}
public void testCase02()
{
final StringBuilder output = new StringBuilder();
Assert.assertTrue(0 == OJ.getSortNum("1234543215555", output) && "4321 1234".equals(output.toString()));
}
public void testCase03()
{
final StringBuilder output = new StringBuilder();
Assert.assertTrue(0 == OJ.getSortNum("12345432155556436567", output) && "6436 4321 1234 67".equals(output.toString()));
}
public void testCase04()
{
final StringBuilder output = new StringBuilder();
Assert.assertTrue(0 == OJ.getSortNum("123454321555000000000056436567", output) && "6436 4321 1234 67 0".equals(output.toString()));
}
public void testCase05()
{
final StringBuilder output = new StringBuilder();
Assert.assertTrue(-1 == OJ.getSortNum("1234543215510000000000000001556436567", output));
}
}