NC182 单词拆分(二) 解题思路

描述

给定一个字符串 s 和一个字符串数组 dic ,在字符串 s 的任意位置添加任意多个空格后得到的字符串集合是给定字符串数组 dic 的子集(即拆分后的字符串集合中的所有字符串都在 dic 数组中),你可以以任意顺序 返回所有这些可能的拆分方案。

数据范围:字符串长度满足 1 \le n \le 20 \1≤n≤20 ,数组长度满足 1 \le n \le 10 \1≤n≤10 ,数组中字符串长度满足 1 \le n \le 20 \1≤n≤20

输入:"nowcoder",["now","coder","no","wcoder"]

返回值:["no wcoder","now coder"]

'''
描述
给定一个字符串 s 和一个字符串数组 dic ,在字符串 s 的任意位置添加任意多个空格后得到的字符串集合是给定字符串数组 dic 的子集(即拆分后的字符串集合中的所有字符串都在 dic 数组中),你可以以任意顺序 返回所有这些可能的拆分方案。

数据范围:字符串长度满足 1 \le n \le 20 \1≤n≤20  ,数组长度满足 1 \le n \le 10 \1≤n≤10  ,数组中字符串长度满足 1 \le n \le 20 \1≤n≤20
'''

#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param s string字符串
# @param dic string字符串一维数组
# @return string字符串一维数组
#
# class Solution:
#     def wordDiv(self , s: str, dic: List[str]) -> List[str]:
#         # write code here

s, dic = "nowcoder",["now","coder","no","wcoder"]    # 测试用例
class Solution:
    def wordDiv(self, s: str, dic):
        # write code here
        sentence_all = []
        while dic:
            sentence = []
            left = 0
            right = 0
            while left < len(s):
                words = set(dic).intersection(set([s[left:right]]))    # 找到交集
                if words:
                    sentence.append(list(words)[0])
                    left = right
                    right += 1
                else:
                    right += 1
            sentence_all.append(' '.join(sentence))
            dic = list(set(dic) - set(sentence))

        return sentence_all

solu = Solution()
solu.wordDiv(s, dic)

测试用例没完全通过

想尝试使用递归但是一直提示

有什么好的办法么

s, dic = "nowcoder",["now","coder","no","wcoder"]
class Solution:

    def __init__(self):
        self.sentence_all = []
    def wordDiv(self, s: str, dic):
        # write code here
        sentence = []
        left = 0
        right = 0
        while left < len(s):
            words = set(dic).intersection(set([s[left:right]]))
            if words:
                sentence.append(list(words)[0])
                left = right
                right += 1
            else:
                right += 1
        self.sentence_all.append(' '.join(sentence))
        dic = list(set(dic) - set(sentence))

        if dic:
            self.wordDiv(s, dic)
        else:
            return self.sentence_all

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值