FRom hackerrank
Steve has a string of lowercase characters in range
ascii[‘a’..’z’]
. He wants to reduce the string to its shortest length by doing a series of operations. In each operation he selects a pair of adjacent lowercase letters that match, and he deletes them. For instance, the string aab
could be shortened to b
in one operation.
Steve’s task is to delete as many characters as possible using this method and print the resulting string. If the final string is empty, print
Empty String.
Input
aaabccddd
Output
abd
Solution in C# -
class Solution { static string superReducedString(string s) { int i = 0; for(; i<s.Length-1;) { if(s[i] == s[i+1]) { if(i<s.Length-2) { s = s.Substring(0,i)+s.Substring(i+2); i = 0; } else { s = s.Substring(0,i); } } else i++; } if(string.IsNullOrEmpty(s)) return "Empty String"; else return s; } static void Main(string[] args) { TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true); string s = Console.ReadLine(); string result = superReducedString(s); textWriter.WriteLine(result); textWriter.Flush(); textWriter.Close(); } }
Post a Comment