• 去连续字符类似删除回文子串问题


    问题:

    随机给一个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         }
    O(n)
     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         }
    递归 简短的做法 就5行代码 效率嘛~~ 呵呵
     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         }
    也是一种思路
    一个苦逼程序员
  • 相关阅读:
    mysql索引的选择
    A、B两个线程交替打印1 -- 100
    dubbo服务暴露
    1
    java无锁化编程一:目录
    如何实现自定义同步组件
    服务器的性能监控
    关于shiro安全框架实现同一用户同一时刻仅可在一个地址登录的技术实现
    关于Spring的Quartz定时器设定
    JAVA之Mybatis基础入门二 -- 新增、更新、删除
  • 原文地址:https://www.cnblogs.com/root_u/p/5126338.html
Copyright © 2020-2023  润新知