Task:

You must write a program that will remove the same, adjacent characters from an arbitrary string. At the same time, if at the removal of these characters a pair of identical adjacent characters again appears, they should also be removed. Here are a few tests to check:

/*balloon -> ban book -> bk affah -> h essence -> nce void Main()*/ { var src = @"balloon-ban book-bk affah-h essence-nce"; var lines = src.Split('\n'); foreach (var line in lines) { var words = line.Trim().Split('-'); Debug.Assert(Foo(words[0]) == words[1], $"Foo({words[0]}) return: { Foo(words[0])}, excpected: {words[1]}"); } } string Foo(string s) { s = Regex.Replace(s,@"\S{2}",""); return s; } 

My method removes all duplicate characters, I can not find the desired pattern

  • Try \S{2,} - nick_n_a
  • one
    \S{2,} as well as \S{2} removes all duplicates, i.e. and the symbols b and a and n, in those cases where they should stay - stasynyo
  • Handbook here is.stackoverflow.com/a/236948/17974 - nick_n_a
  • Take the line abaabc what should be left of it? - Mike
  • one
    @Mike, by condition - ac . That is: $s =~ s/(.)\1+//g while $s =~ /(.)\1/; - PinkTux

1 answer 1

For example, you can do this with a loop that breaks as soon as another replacement changes nothing:

 string Foo(string s){ string p; do { p = s; s = Regex.Replace(s, @"(.)\1+", ""); } while (s != p); return s; } 
  • Yes. without a loop there are duplicate characters that appeared after replacing already - stasynyo