如何对包含特殊字符的数组按字母顺序排序?



我正在寻找根据某种格式准备的以下字符串在标准输出中产生以下输出的代码。

假设和规则:

  • 每个字母在给定字符串中使用2次,相同两个字母之间的字母被视为字母。
  • 给定的字符串总是以适当的格式给出。字符串格式不需要检查

例子:

输入>:abccbdeeda

预期输出:

a
--b
----c
--d
----e

解释:自从那两个字母"b"出现在字母"a"之间,字母b需要两个连字符(--b)

尝试
public static void main(String[] args) {
String input = "abccbdeeda";
System.out.println("input: " + input);
String[] strSplit = input.split("");
String g = "";
String h = "-";
ArrayList<String> list = new ArrayList<String>();
int counter = 1;
boolean secondNumber;
list.add(strSplit[0]);
int dual = 0;
for (int i = 1; i < strSplit.length; i++) {
secondNumber = list.contains(strSplit[i]);
if ((secondNumber)) {
counter--;
dual = counter * 2;
for (int f = 0; f < dual; f++) {
strSplit[i] = h.concat(strSplit[i]);
}
g = "";
dual = 0;
} else {
list.add(strSplit[i]);
counter++;
}
}
Arrays.sort(strSplit);
for (int p = 0; p < strSplit.length; p++) {
System.out.println(strSplit[p]);
}
}

输入:abccbdeeda

我输出:

----c 
----e 
--b 
--d 
a 

我无法按字母顺序对输出进行排序。如何按字母顺序对其中的连字符进行排序?

这个任务在堆栈的帮助下很好地完成了。如果当前字符等于堆栈的顶部,那么该字符是关闭的,可以被删除,否则我们第一次遇到它,它必须被添加到堆栈和结果字符串中,在它之前添加stack.size() * 2破折号。

当完全遍历字符串后,可以对结果字符串进行排序。

public static void main(String[] args) {
Stack<Character> stack = new Stack<>();
String string = "abccbdeeda";
StringBuilder result = new StringBuilder();
for(int i = 0; i < string.length(); i++) {
char curChar = string.charAt(i);
if(!stack.isEmpty() && curChar == stack.peek()) {
stack.pop();
} else {
result.append("-".repeat(stack.size() * 2)).append(curChar).append(" ");
stack.add(curChar);
}
}
System.out.println(result);
System.out.println(Arrays.toString(Arrays.stream(result.toString().split(" ")).sorted().toArray()));
}

输出
a --b ----c --d ----e 
[----c, ----e, --b, --d, a]

您可以遍历strSplit数组并将每个元素中的字符提取到单独的列表/数组中。如果需要检查数组元素中是否包含字母,可以使用正则表达式。例:private final Pattern x = Pattern.compile("[a-z]");

编写一个单独的方法来匹配strSplit数组中的每个元素的模式。此方法将返回输入字符串中的字符。

private String findCharactor(final StringBuilder element) {
final Matcher matcher = x.matcher(element);
if (matcher.find()) {
final int matchIndex = matcher.start(); //this gives the index of the char in the string
return element.substring(matchIndex); 
}
}

将这些返回的字符添加到一个单独的数组中,并使用排序函数对其进行排序。

假设您的结果列表为:

List<String> resultList = Arrays.asList("----c", "----e", "--b", "--d", "a");

您可以按字母顺序按单行排序:

Collections.sort(resultList, (o1, o2) -> new StringBuilder(o1).reverse().toString().compareTo(new StringBuilder(o2).reverse().toString()));

可以使用递归进行深度优先遍历(preorder):

public static String dfs(String string, String prefix) {
if (string.length() == 0) return "";
int i = string.indexOf(string.charAt(0), 1);
return prefix + string.charAt(0) + "n"             // current
+ dfs(string.substring(1, i), prefix + "--") // all nested
+ dfs(string.substring(i + 1), prefix);      // all siblings
}

示例调用:

public static void main(String[] args) {
System.out.println(dfs("abccbdeeda", ""));
}

最新更新