如何按照指定字符串数组模式对单词字符串进行排序
Sort String of Words by Custom Predefined Pattern Order
Alright, let's tackle this problem where we need to sort a space-separated string of words strictly according to the order defined in a given pattern array. The goal is to group identical words together and arrange all groups following the sequence in the pattern.
Step-by-Step Approach
- Map Pattern to Priority: First, we create a lookup map that assigns each word in the pattern a priority value (its index in the pattern array). This lets us quickly determine the order of any word during sorting.
- Split Input String: Break the input string into an array of individual words using space as the delimiter.
- Sort with Custom Comparator: Use the priority map to sort the word array—words with lower priority values (earlier in the pattern) come first.
- Reconstruct Result String: Join the sorted word array back into a single space-separated string.
Java Implementation
Here's a complete working example that matches your input and expected output:
import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class PatternWordSorter { public static void main(String[] args) { // Predefined pattern order String[] pattern = {"Burger", "Fries", "Chicken", "Pizza", "Sandwich", "Onionrings", "Milkshake", "Coke"}; // Input string to sort String input = "Chicken Coke Chicken Chicken Onionrings Coke Burger Milkshake Milkshake Burger Coke Milkshake Burger Onionrings Onionrings Coke Chicken Burger Fries Milkshake"; // Build priority map: word -> its position in the pattern Map<String, Integer> priorityMap = new HashMap<>(); for (int i = 0; i < pattern.length; i++) { priorityMap.put(pattern[i], i); } // Split input into words String[] words = input.split(" "); // Sort words using the pattern's priority Arrays.sort(words, (wordA, wordB) -> priorityMap.get(wordA) - priorityMap.get(wordB)); // Join sorted words into the result string String sortedResult = String.join(" ", words); // Print or return the result System.out.println(sortedResult); // Output matches your expected string: "Burger Burger Burger Burger Fries Chicken Chicken Chicken Chicken Onionrings Onionrings Onionrings Milkshake Milkshake Milkshake Milkshake Coke Coke Coke Coke" } }
Key Notes
- Efficiency: Using a hash map for priority lookup ensures each comparison during sorting is O(1), making the overall time complexity O(n log n) (dominated by the sorting step), where n is the number of words.
- Handling Edge Cases: If your input might contain words not present in the pattern, you can adjust the comparator to handle them—for example, pushing unknown words to the end, or throwing an exception if invalid words aren't allowed. In this case, we assume all input words are in the pattern.
内容的提问来源于stack exchange,提问作者Arthur
相关产品推荐
相关产品推荐

