去连续字符类似删除回文子串问题
问题:
随机给一个string,去掉连续重复字符后新的字符串有连续重复字符继续去掉,直到没有连续在一起的相同字符,比如180008935531,最后变成191。
算法复杂度要求为O(n)
1 private static void ttss(string str) 2 { 3 string op = ""; 4 for (int i = 0; i < str.Length; i++) 5 { 6 if (! ((i!=0&&str[i]==str[i-1]) ||(i!=str.Length-1&&str[i]==str[i+1]))) 7 { 8 if (!(op.Count() != 0 && op.Last() == str[i])) 9 { 10 op += str[i]; 11 } 12 else 13 { 14 op = op.Substring(0, op.Length - 1); 15 } 16 } 17 } 18 19 Console.Write(op); 20 21 }
1 private static string GetStr(string str) 2 { 3 for (int i = 0; i < str.Length - 1; i++) 4 { 5 int len = 1; 6 while (str[i] == str[i + len]) len++; 7 if (len > 1) return GetStr(str.Remove(i, len)); 8 } 9 return str; 10 }
1 private static void jsnm(String str) 2 { 3 char loc = '@'; 4 bool mat = false; 5 for (int i = 0; i < str.Length - 1; i++) 6 { 7 if (str[i] == str[i + 1]) 8 { 9 loc = str[i]; 10 str = str.Remove(i + 1, 1); 11 i = i - 1; 12 mat = true; 13 } 14 else 15 { 16 if (mat) 17 { 18 loc = str[i - 1]; 19 str = str.Remove(i, 1); 20 i = i - 2; 21 } 22 mat = false; 23 } 24 } 25 Console.Write(str); 26 }
一个苦逼程序员