- Sample Input
-
aabbccdd 007799aabbccddeeff113355zz 1234.89898 abcdefabcdefabcdefaaaaaaaaaaaaaabbbbbbbddddddee
- Sample Output
-
abcdabcd 013579abcdefz013579abcdefz <invalid input string> abcdefabcdefabcdefabdeabdeabdabdabdabdabaaaaaaa
Description
For this question, your program is required to process an input string containing only ASCII characters between ‘0’ and ‘9’, or between ‘a’ and ‘z’ (including ‘0’, ‘9’, ‘a’, ‘z’).
Your program should reorder and split all input string characters into multiple segments, and output all segments as one concatenated string. The following requirements should also be met,
1. Characters in each segment should be in strictly increasing order. For ordering, ‘9’ is larger than ‘0’, ‘a’ is larger than ‘9’, and ‘z’ is larger than ‘a’ (basically following ASCII character order).
2. Characters in the second segment must be the same as or a subset of the first segment; and every following segment must be the same as or a subset of its previous segment.
Your program should output string “<invalid input string>” when the input contains any invalid characters (i.e., outside the '0'-'9' and 'a'-'z' range).
Input
Input consists of multiple cases, one case per line. Each case is one string consisting of ASCII characters.
Output
For each case, print exactly one line with the reordered string based on the criteria above.
我的水平有限,但最终也解答出来了。下面贴出个人的答案,欢迎大牛批评指正。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StringReorder { class Program { static void Main(string[] args) { string input = string.Empty; input = Console.ReadLine(); GetResults(input); } static void GetResults(string input) { string results = ""; if (MatchRequirement(input)) { List<char> inputCharList = sort(input).ToList(); List<char> tempList = new List<char>(); while (inputCharList.Count > 0) { tempList.Add(inputCharList[0]); inputCharList.RemoveAt(0); int i = 0; while (i < inputCharList.Count) { if (inputCharList[i] > tempList[tempList.Count - 1]) { tempList.Add(inputCharList[i]); inputCharList.RemoveAt(i); } else { i++; } } results += ListToString(tempList); tempList.Clear(); } Console.WriteLine(results); } } static string ListToString(List<char> tempList) { string tempStr = ""; for (int i = 0; i < tempList.Count; i++) { tempStr += tempList[i]; } return tempStr; } static string sort(string inputString) { char[] inputChars = inputString.ToArray(); string tempStr = ""; Array.Sort(inputChars); for (int i = 0; i < inputChars.Length; i++) { tempStr += inputChars[i]; } return tempStr; } static bool MatchRequirement(string inputString) { bool tempValue = false; char[] inputChars = inputString.ToArray(); for (int i = 0; i < inputChars.Length; i++) { if (!match(inputChars[i])) { Console.WriteLine("<invalid input string>"); tempValue = false; break; } else { tempValue = true; } } return tempValue; } static bool match(char c) { if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z')) { return true; } return false; } } }