BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / python / #10829同步于 2016/1/5
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖

同样的算法为啥python过不了java能通过

iamluo
2016/1/5镜像同步3 回复
leetcode第10题,匹配字符串。。。 python代码: class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ sLen = len(s) pLen = len(p) if (pLen == 0): return sLen == 0 if (pLen == 1): if (p == s) | ((p == '.') & (len(s) == 1)): return True else: return False if (p[1] == '*'): while (len(s) > 0) & ((p[0]==s[0]) | (p[0]=='.')): if (self.isMatch(s,p[2:])): return True s = s[1:] return self.isMatch(s,p[2:]) else: if (len(s) > 0) & ((p[0]==s[0]) | (p[0]=='.')): return self.isMatch(s[1:],p[1:]) return False 【提交报错】Line 18: IndexError: string index out of range Java代码: public class Solution { public boolean isMatch(String s, String p){ int sLen = s.length(); int pLen = p.length(); if(pLen == 0) return sLen == 0; if(pLen == 1){ if(p.equals(s) || p.equals(".") && s.length() == 1) return true; else return false; } if(p.charAt(1) == '*'){ //p的下个字符是'*',如果p和s当前字符相同或p当前字符是'.',则一直往右移动 while (s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.' )){ if(isMatch(s,p.substring(2))) return true; s = s.substring(1); } return isMatch(s,p.substring(2)); } else{ //p的下个字符不是'*',如果p和s当前字符相同或p当前字符是'.',则p和s往右移动一个字符 if(s.length() > 0 && (p.charAt(0) == s.charAt(0) || p.charAt(0) == '.')){ return isMatch(s.substring(1),p.substring(1)); } return false; } } } 【提交成功】
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
nuanyangyang机器人#1 · 2016/1/5
不是&,是and
iamluo机器人#2 · 2016/1/5
【 在 nuanyangyang 的大作中提到: 】 : 不是&,是and 多谢暖神提醒,改过来后可以,But Time Limit Exceeded 难道python不适合用递归?
nuanyangyang机器人#3 · 2016/1/5
【 在 iamluo 的大作中提到: 】 : 多谢暖神提醒,改过来后可以,But Time Limit Exceeded : 难道python不适合用递归? 如果爆栈了会抛运行时异常。检查你的算法复杂度吧。留意一下会拷贝多少字符串。Python字符串不可变,小心一点。