Thursday, August 15, 2013

public static string ReverseWords(string s)
{
 var sb = new StringBuilder(s);
 Reverse(sb, 0, sb.Length - 1);
 int start = 0;
 int end = 0;
 for (int i = 1; i < sb.Length; i++)
 {
  if (sb[i - 1] != ' ')
  {
   end++;
   if (sb[i] != ' ')
   {
    continue;
   }
  }
  else
  {
    start = i;
    end = i;
  }
  Reverse(sb, start, end - 1);
  start = i;
  end = i;
 }
 Reverse(sb, start, end);
 return sb.ToString();
}

private static void Reverse(StringBuilder sb, int start, int end)
{
 while (start < end)
 {
  var c = sb[end];
  sb[end] = sb[start];
  sb[start] = c;
  end--;
  start++;
 }
}

Some sample test cases:
string s = "The quick brown fox jumped over the trot";Debug.Assert(s == ReverseWords(ReverseWords(s))) ;Debug.Assert("" == ReverseWords(ReverseWords("")));Debug.Assert("abc" == ReverseWords(ReverseWords("abc")));Debug.Assert("ab bc" == ReverseWords(ReverseWords("ab bc")));Debug.Assert(" ab " == ReverseWords(ReverseWords(" ab ")));Debug.Assert("ab " == ReverseWords(ReverseWords("ab ")));Debug.Assert(" ab" == ReverseWords(ReverseWords(" ab")));

No comments:

Post a Comment