s 为'eccer', s[3:0:-1]为'ecc',而 s[3:-1:-1]却是'',而不是我期望的'ecce'?

320 天前
 JasonLaw

难道是 s[3:-1:-1]等价于 s[3:4:-1]?所以结果为''?


关联的 LeetCode problem: Valid Palindrome II - LeetCode

我的出现错误的 solution 。

class Solution:
    def validPalindrome(self, s: str) -> bool:
        l, r = 0, len(s) - 1
        while l < r:
            if s[l] != s[r]:
                return s[l + 1:r + 1] == s[r:l:-1] or s[l:r] == s[r - 1:l - 1:-1]
            l += 1
            r -= 1
        return True
1104 次点击
所在节点    Python
7 条回复
luozic
320 天前
luozic
320 天前
+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
mkroen
319 天前
s[3::-1]
JasonLaw
319 天前
@luozic #2 按照正常理解的话,我会觉得 s[3:-1:-1]的结果是'e'+'c'+'c'+'e',不包含'r',因为它是 stop index 所在的 char 。
JasonLaw
319 天前
@mkroen #3 我知道这样子可以,但是这样子我的代码就会变得复杂。我需要判断 stop 是否为-1 ,如果是-1 的话,就需要使用 s[3::-1]替代 s[3:-1:-1]。
zizon
319 天前
s[3:-1:-1]
-> s[3:4:-1]
-> s[4:3:1]
-> s[4:3] , 4 > 3
evemoo
319 天前
左闭右开 + 切片的顺序 = 答案

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/951262

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX