我尝试使用正则表达式在python 2.7中解决这个问题。我发现它很简单。想知道我是否遗漏了什么。这里有边缘表壳或表壳吗?
S = "abppplee"
D = {"able", "ale", "apple", "bale", "kangaroo"}
def subseq(S,D):
# every word in D is made into a regex pattern interspersed with .* and looked up in S
import re
in_dict = {word:len(word) for word in D if bool(re.search(pattern=".*".join(word),string=S))}
return max(in_dict, key=in_dict.get)
subseq(S,D)
返回'apple'
答案 0 :(得分:0)
扫描字符串以查找与模式匹配的内容,返回匹配对象,如果未找到匹配项则扫描无。
但在你的情况下,你需要找到带有列表的字符串的子序列。 生成子序列的代码是
def subsequence(X, Y, m, n):
L = [[0 for x in range(n + 1)] for x in range(m + 1)]
# Following steps build L[m+1][n+1] in bottom up fashion. Note
# that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
# Following code is used to print LCS
val = L[m][n]
index = L[m][n]
# Create a character array to store the lcs string
lcs = [""] * (index + 1)
lcs[index] = "\0"
# Start from the right-most-bottom-most corner and
# one by one store characters in lcs[]
i = m
j = n
while i > 0 and j > 0:
# If current character in X[] and Y are same, then
# current character is part of LCS
if X[i - 1] == Y[j - 1]:
lcs[index - 1] = X[i - 1]
i -= 1
j -= 1
index -= 1
# If not same, then find the larger of two and
# go in the direction of larger value
elif L[i - 1][j] > L[i][j - 1]:
i -= 1
else:
j -= 1
sequence = "".join(lcs)
return val,sequence
#Driver Code
S = "alnegearoo"
D = {"able", "ale", "apple", "bale", "kangaroo"}
max_len = 0
max_string = ""
for word in D:
subseq_len,match = subsequence(word,S,len(word),len(S))
if(max_len < subseq_len):
max_len = subseq_len
max_string = match
print(max_string)
angaroo
享受编码......
答案 1 :(得分:0)
我是用java做的,希望它能帮助别人解决它
import React, { Component } from 'react';
import {
Text,
View,
ScrollView
} from 'react-native';
const text = ".\n".repeat(600)
export default class App extends Component {
render() {
return (
<View style={{
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}}>
<ScrollView style={{flex: 1}}>
<Text>{text}</Text>
</ScrollView>
</View>
);
}
}
答案 2 :(得分:0)
您应该使用re.escape
。
import re
string = 'abppplee{lkfj3lkj.f*)(*)(*@}dddd.sdf*3j3jj3}@@@@'
words = {'apple', 'ale', 'bale', 'able', 'apple{}.*', 'kangaroo'}
max({word for word in words
if re.search('.*'.join(map(re.escape, word)), string)},
key=len)
我很难区分回答这个问题和例如做Kata。 Codewars。