Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/c695be78345751a5f389ba3332c33342 to your computer and use it in GitHub Desktop.
Save jianminchen/c695be78345751a5f389ba3332c33342 to your computer and use it in GitHub Desktop.
HackerRank - String - Reverse Shuffle Merge - a practice - take more than 30 minutes to write, debug, look up internet, run on HackerRank.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace reverseShuffleMerge_Practice2
{
class Program
{
static void Main(string[] args)
{
string[] testCases = new string[4] { "abcacb", "aaccbb", "cacbab", "baabcc"};
List<string> outputStrs = new List<string>();
foreach (string s in testCases)
{
string s2 = reverseShuffleMerge(s);
outputStrs.Add(s2);
}
string[] result = outputStrs.ToArray();
}
/*
* practice on May 26, 2016
* Need to walk through the code, and examine the code
*
* Look up the C# string - how to reverse a string
* http://stackoverflow.com/questions/228038/best-way-to-reverse-a-string
*/
public static string reverseShuffleMerge(string input)
{
if (input == null || input.Length == 0)
return null;
int TOTALCHARS = 26;
int[] add = new int[TOTALCHARS];
int[] skip = new int[TOTALCHARS];
foreach (char c in input)
{
skip[c - 'a']++;
}
for (int i = 0; i < TOTALCHARS; i++)
{
skip[i] = skip[i] / 2;
add[i] = skip[i];
}
Stack<char> stack = new Stack<char>();
int len = input.Length;
for (int i = len - 1; i >= 0; i--) // reverse
{
char runner = input[i];
int index = runner - 'a';
// stack keeps popping out until it is ready for runner
while (stack.Count > 0 &&
add[index] > 0 &&
( (char)stack.Peek() > runner) &&
(skip[(char)stack.Peek() - 'a'] > 0) )
{
char c = stack.Pop();
add[c-'a'] ++;
skip[c - 'a']--; // bug: failed test case: "abcacb", output: ab. Should be --
}
if (add[index] > 0)
{
stack.Push(runner);
add[index]--;
}
else
skip[index]--; // bug - skip[] - how many left to be skipped
}
char[] output = stack.ToArray();
Array.Reverse(output);
return new string(output);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment