Trimming duplicate characters with single character in string

  • A+
Category:Languages

This was a interview question - How will you efficiently trim the duplicate characters in string with single character.

Example: suppose this is the input string

"reeeturrrnneedd"

The output should be:

"returned"

I explained it by using splitting the string and loop through the char array, but interviewer does not convinced with the answer said this is not the efficient way.

private void test() {     string s = "reeeturrrnneeddryyf";     StringBuilder sb = new StringBuilder();     char pRvChar = default(char);     foreach (var item in s.ToCharArray())     {                         if (pRvChar == item)         {             continue;         }         pRvChar = item;         sb.Append(pRvChar);     }      MessageBox.Show(sb.ToString()); } 

Then I thought about Linq to object and use distinct but it will give incorrect output as it remove all duplicate characters and output will be "retund"

Can someone tell me the more efficient way to do it?


Here's a solution with regex:

Regex regex = new Regex( "(.)//1+" ); string result = regex.Replace( s,"$1" ); 

I'm not sure, if this is more efficient that your 'for' loop in terms of execution time, but it is more efficient in terms of developer work. And easy to read, at least for people familiar with regex.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: