循环单词(LintCode)

计算数组中不同的旋转字符串个数;旋转字符串定义为str1经右旋转后可以得到str2,str1和str2即为相同的旋转字符串。

eg:picture和turepic即为相同旋转字符串

样例

Given dict = ["picture", "turepic", "icturep", "word", "ordw", "lint"]
return 3.

分析最基本的思路:

    1.循环判断当前字符串和前面的字符串是否为旋转字符串;

    2.如果是就删除;

    3.返回剩余字符串个数。

代码如下:

    public int CountRotateWords(string[] strs)
    {
        List<string> strList = strs.ToList();
        for (int i = 0; i < strList.Count; i++)
        {
            for (int j = i + 1; j < strList.Count;)
            {
                if (CountRotateWordsHelper(strList[i], strList[j]))
                {
                    strList.RemoveAt(j);               //调用RemoveAt方法后list.Count会减小,为了防止元素遍历时候被漏掉索引不自增
                }
                else
                {
                    j++;                               //不是旋转字符串时候索引自增
                }
            }
        }

        return strList.Count;
    }
下面是判断是否是旋转字符串的方法:
    public bool CountRotateWordsHelper(string str1, string str2)
    {
        if (str1.Length != str2.Length) return false;
        str2 += str2;                                              //将str2扩容
        if (str2.Contains(str1))                                   //判断扩容后的str2是否含有str1
            return true;
        return false;
    }

按照自己的思路实现算发只能通过88%的测试数据,显示Memory Limit Exceeded,还是算法的空间复杂度太大造成内存溢出

扫描二维码关注公众号,回复: 183924 查看本文章

后来看了官方的思路

如下:

    public int CountRotateWords(string[] strs)
    {
         //官方解法
        List<string> strList=new List<string>();
        foreach (string item in strs)
        {
            string s = item + item;                               //扩容
            for (int i = 0; i < item.Length; i++)
            {
                strList.Remove(s.Substring(i, item.Length));      //除去重复字符串
            }
            strList.Add(item);                                    //保证去除重复过后必须保留一个
        }
        return strList.Count;
    }
完美解决问题。。。。。代码简单易懂,不得不佩服!!!


猜你喜欢

转载自blog.csdn.net/Wenbooboo/article/details/80229573