python学习(二十三)

来源:互联网 发布:淘宝网衣服女装休闲裙 编辑:程序博客网 时间:2024/05/16 13:02

  • Valid Anagram
    • 题目
    • 思路与解答
    • 答案
  • Valid Palindrome
    • 题目
    • 思路与解答
    • 答案
  • Valid Palindrome II
    • 题目
    • 思路与解答
    • 答案
  • Valid Parentheses
    • 题目
    • 思路与解答
    • 答案
  • Valid Perfect Square
    • 题目
    • 思路与解答
    • 答案

注意,答案只是代表是他人写的代码,正确,但不一定能通过测试(比如超时),列举出来只是它们拥有着独到之处,虽然大部分确实比我的好

242. Valid Anagram

题目

Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

思路与解答

不是很懂啥意思?
是s和t使用了相同的字符?
set喽
好像还要求字符数相等?
dict呗

        ds,dt = {},{}        for w in s:            ds[w] = ds.get(w,0)+1        for w in t:            dt[w] = dt.get(w,0)+1        return ds == dt

答案

啊,我也想过用sorted做。。。但是一闪而过又忘记了?

return sorted(s) == sorted(t)
return all([s.count(c)==t.count(c) for c in string.ascii_lowercase])
return collections.Counter(s)==collections.Counter(t)

真是各种一行方案啊
看到有人说一个dict就能解决,想了一下是的

        #是我写的        d = {}        for w in s:            d[w] = d.get(w,0)+1        for w in t:            d[w] = d.get(w,0)-1            if not d[w]:del d[w]        return not d

125. Valid Palindrome

题目

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
“A man, a plan, a canal: Panama” is a palindrome.
“race a car” is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

思路与解答

那个例子举得我有些不懂呢???
“A man, a plan, a canal: Panama” is a palindrome.
Why???
哦,只要求字母对称就可以了啊
判断是不是字母我记得有个函数来着

        n=[i.lower() for i in s if i.isalnum()]        return n == n[::-1]

答案

指针方案,没有去考虑这么写(因为毕竟麻烦)

def isPalindrome(self, s):    l, r = 0, len(s)-1    while l < r:        while l < r and not s[l].isalnum():            l += 1        while l <r and not s[r].isalnum():            r -= 1        if s[l].lower() != s[r].lower():            return False        l +=1; r -= 1    return True

我也看到和我一样的方法了,不过好像被批评了?

680. Valid Palindrome II

题目

Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.

Example 1:
Input: “aba”
Output: True
Example 2:
Input: “abca”
Output: True
Explanation: You could delete the character ‘c’.
Note:
The string will only contain lowercase characters a-z. The maximum length of the string is 50000.

思路与解答

卧槽,如果每删一个对比一次。。。感觉会超时的吧
不对,先比较回文,出错再考虑方案
这样就要用到之前的指针方案了
在处理第一个错误那里出现了问题,怎么保证你删的那个是对的呢。。。感觉要完全比较下去

        def huiwen(n,f):                   l,r = 0, len(n)-1            while l < r:                if n[l]!= n[r]:                    if f:                        return huiwen(n[l+1:r+1],0) or huiwen(n[l:r],0)                    else:                        return False                l += 1                r -= 1            return True        return huiwen(s,1)

因为要套几遍,所以我直接写个函数了
可惜速度不行啊

答案

emmmm为啥我要去用指针呢?

        rev = s[::-1]        if s == rev: return True        l = len(s)        for i in xrange(l):            if s[i] != rev[i]:                return s[i:l-i-1] == rev[i+1:l-i] or rev[i:l-i-1] == s[i+1:l-i]        return False

差不多的方案

def validPalindrome(self, s):        i = 0        while i < len(s) / 2 and s[i] == s[-(i + 1)]: i += 1        s = s[i:len(s) - i]        return s[1:] == s[1:][::-1] or s[:-1] == s[:-1][::-1]

20. Valid Parentheses

题目

Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.

The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.

思路与解答

堆栈?
如何将字典里的两个括号关联起来?
不能根据values查找key。。。。
d.items()怎么不对??
好像可以去掉,后面还有判断的

        stack=[]        d={")":"(","}":"{","]":"["}        for n in s:            if n in d.values():                stack.append(n)            elif n in d.keys():                if not stack:return False                x = stack.pop()                if x != d[n]:                    return False            else:                return False        return stack == []

速度还行

答案

差不多嘛(但是比我的短)

        stack = []        pairs = {'(': ')', '{': '}', '[': ']'}        for char in s:            if char in pairs:                stack.append(pairs[char])            else:                if len(stack) == 0 or stack.pop() != char:                    return False        return not stack

367. Valid Perfect Square

题目

Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Example 1:

Input: 16
Returns: True
Example 2:

Input: 14
Returns: False

思路与解答

意思是这个数是不是其它整数的平方?
感觉需要搜一下判断方法
完全平方数等于1+3+5+7+9+….+2n-1
比暴力版快

        n=1        while num > 0:            num -= n+n-1            n += 1        return num == 0

别人有更快的,估计是方法不一样

答案

emmm就是之前的某个公式,居然比我的快

    def isPerfectSquare(self, num):        x = num        r = x        while r*r > x:            r = (r + x/r) / 2        return r*r == x
原创粉丝点击