zoukankan      html  css  js  c++  java
  • 171. 乱序字符串

    171. 乱序字符串

    中文English

    给出一个字符串数组S,找到其中所有的乱序字符串(Anagram)。如果一个字符串是乱序字符串,那么他存在一个字母集合相同,但顺序不同的字符串也在S中。

    样例

    样例1:

    输入:["lint", "intl", "inlt", "code"]
    输出:["lint", "inlt", "intl"]
    

    样例 2:

    输入:["ab", "ba", "cd", "dc", "e"]
    输出: ["ab", "ba", "cd", "dc"]
    

    挑战

    什么是Anagram?

    • 如果在更改字符顺序后它们可以相同,则两个字符串是anagram。

    注意事项

    所有的字符串都只包含小写字母

    输入测试数据 (每行一个参数)如何理解测试数据?

    第一个版本:你的代码运行时间超过了限制,检查你的时间复杂度。TLE通常是由死循环造成的,思考一下你的时间复杂度是否是最优的。

    class Solution:
        """
        @param strs: A list of strings
        @return: A list of strings
        """
        '''
        大致思路:
        1.给出一个方法,判断两个字符串是否是乱序相等
        2.初始化res,while strs不为空的时候,内层循环,pop值进行判断,符合写入res,返回
        '''
        def anagrams(self, strs):
            res = []
            isEq = False
            while strs != []:
                p = strs.pop(0)
                if p in res:
                    continue
                for s in strs:
                    if self.isEqual(p,s) == True:
                        res.append(s)
                        isEq = True
                if isEq == True:
                    res.append(p)
                isEq = False
            return res
    
                
        def isEqual(self,s1,s2):
            while s1 != '':
                p = s1[0]
                if p in s2:
                    s2 = s2.replace(p,'',1)
                else:
                    return False
                s1 = s1.replace(p,'',1)
            return True if s2 == '' else False

     第二个版本:字典写法(lintcode通过)

    class Solution:
        """
        @param strs: A list of strings
        @return: A list of strings
        """
        '''
        大致思路:
        1.首先给出字典,{sortword:[xx,xx]}
        2.循环字典k,v,如果v的长度大于1,则写入res里面
        '''
        def anagrams(self, strs):
            dic = {}
            res = []
            for word in strs:
                sortedword =  ''.join(i for i in sorted(word))
                dic[sortedword] = [word] if sortedword  not in dic.keys() else dic[sortedword] + [word]
            
            #对dic操作
            for k,v in dic.items():
                if len(v) > 1:
                    res.extend(v)
            return res 
  • 相关阅读:
    Percona: How to Restore MySQL Logical Backup at Maximum Speed
    MySQL之UNDO及MVCC、崩溃恢复
    MySQL checkpoint深入分析
    关于MySQL latch争用深入分析与判断
    InnoDB关键特性之刷新邻接页-异步IO
    InnoDB关键特性之自适应hash索引
    MySQL后台线程的清理工作
    MySQL IO线程及相关参数调优
    MySQL存储写入性能严重抖动分析
    MySQL的SQL预处理(Prepared)
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12834066.html
Copyright © 2011-2022 走看看