You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

含转义/特殊字符的字符串数组求最长公共前缀返回空的问题

最长公共前缀函数处理特殊字符串返回空的问题

我编写的Python函数在普通字符串数组中能正常查找最长公共前缀:

def longestCommonPrefix(S) :
    if (len(S) == 0):
        return ""
    for i in range(len(S[0])):
        c = S[0][i]
        for j in range(len(S)):
            if (i == len(S[j]) or S[j][i] != c):
                return S[0][0:i];             
    return S[0]

X = ["Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt anim id est laborum.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod td exercitation ullamcon reprehenderit int occaecat cupidatat nonmollit anim id est laborum.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, ccaecat cupidatat nonmollit anim id est laborum.",
"Lorem ipsum dolor sit amet, consectetur adrit int occaecat cupidatat nonmollit anim id est laborum."]

print(longestCommonPrefix(X))

>> 'Lorem ipsum dolor sit amet, consectetur ad'

但处理包含换行符、LaTeX公式等特殊内容的字符串数组时,函数返回空字符串''。示例数组如下:

X = [
'Class- VII-CBSE-Mathematics\\nIntegers\ne EMBIBE\nThe temperature at Srinagar \\( =-2^{\\circ} \\mathrm{C} \\)\nTherefore, the difference \\( =-2^{\\circ} \\mathrm{C}-\\left(-8^{\\circ} \\mathrm{C}\\right) \\) \\( =6^{\\circ} \\mathrm{C} \\)\n(d) The temperature of Srinagar and Shimla taken together \\( =-2^{\\circ} \\mathrm{C}+5^{\\circ} \\mathrm{C} \\) \\( =3^{\\circ} \\mathrm{C} \\)\nThe temperature at Shimla \\( =5^{\\circ} \\mathrm{C}>3^{\\circ} \\mathrm{C} \\). Therefore the temperature of Srinagar and Shimla taken together is less than that of Shimla.\n\nThe temperature at Srinagar \\( =-2^{\\circ} \\mathrm{C}<3^{\\circ} \\mathrm{C} \\). Therefore, the temperature of Srinagar and Shimla taken together is not less than that of Srinagar',
'Class- VII-CBSE-Mathematics\\nIntegers\ne EMBIBE\nSubmarine floating below the sea level \\( =1200 \\mathrm{~m} \\)\nTherefore, the vertical distance between them \\( =5000+1200 \\)\n\\[\n=6200 \\mathrm{~m}\n\\]',
'Class- VII-CBSE-Mathematics\\nIntegers\ne EMBIBE\n\\begin{tabular}{|c|c|c|}\n\\hline\\( -4 \) & \\( -3 \) & \\( -2 \\\\\n\\hline\\( -6 \) & 4 & \\( -7 \\\\\n\\hline\n\\end{tabular}', '\n(i) Sum of the rows:\n\\[\n\\begin{array}{l}\n5+-1+-4=0 \\\\\n-5+-2+7=0 \\\\\n0+3+-3=0\n\\end{array}\n\\]\nSum of the columns:\n\\[\n\\begin{array}{l}\n5+-5+0=0 \\\\\n-1+-2+3=0 \\\\\n-4+7+-3=0\n\\end{array}\n\\]\nSum of the diagonals:\n\\[\n\\begin{array}{l}\n5+-2+-3=0 \\\\\n-4+-2+0=-6\n\\end{array}\n\\]\nThus, this is not a magic square because all the sums are not equal\n(ii) Sum of the rows:\n\\[\n\\begin{array}{l}\n1+-10+0=-9 \\\\\n-4+-3+-2=-9 \\\\\n-6+4+-7=-9\n\\end{array}\n\\]\nSum of the columns:\n\\[\n\\begin{array}{l}\n1+-4+-6=-9 \\\\\n-10+-3+4=-9 \\\\\n0+-2+-7=-9\n\\end{array}\n\\]\nSum of the diagonals:\n\\[\n\\begin{array}{l}\n1+-3+-7=0 \\\\\n0+-3+-6=-9\n\\end{array}\n\\]\nThus, this is a magic square because all the sums are equal',
'Class- VII-CBSE-Mathematics\\nIntegers\ne EMBIBE\n(ii) \\( a=118, b=125 \\)\n(iii) \\( \\mathrm{a}=75, \\mathrm{~b}=84 \\)\n(iv) \\( a=28, b=11 \\)', '\n\\[\n\\begin{array}{l}\n\\text { LHS } a-(-b)=21-(-18)=39 \\\\\n\\text { RHS } a+b=21+18=39 \\\\\n\\mathrm{LHS}=\\text { RHS }\n\\end{array}\n\\]\nThus verified\n\\[\n\\begin{array}{l}\n\\operatorname{LHS~} a-(-b)=118-(-125)=243 \\\\\n\\text { RHS a }+b=118+125=243 \\\\\n\\mathrm{LHS}=\\text { RHS }\n\\end{array}\n\\]\nThus verified\n\\[\n\\begin{array}{l}\n\\operatorname{LHS~} a-(-b)=75-(-84)=159 \\\\\n\\text { RHS } a+b=75+84=159 \\\\\n\\text { LHS }=\\text { RHS }\n\\end{array}\n\\]\nThus verified\n\\[\n\\begin{array}{l}\n\\operatorname{LHS~} a-(-b)=28-(-11)=39 \\\\\n\\text { RHS } a+b=28+11=39\n\\end{array}\n\\]\n\\[\n\\mathrm{LHS}=\\mathrm{RHS}\n\\]\nThus verified',
'Class- VII-CBSE-Mathematics\\nIntegers\ne EMBIBE\n(c) \\( -7>-29 \\)\n(d) \\( 0<20 \\)\n(e) \\( -101>-159 \\)',
] 

我尝试过两种处理方式,但都无法解决问题:

  • 替换特殊字符:
def replace(x):
    for i in ["\\","\n","\t",'\"',"\'","\b","\f","\r"]:
        x = x.replace(i,"`")
    return x

X = [replace(i) for i in X]
  • 使用repr()转换字符串:
X = [repr(i) for i in X]

函数仍然返回空字符串,求解决办法。


问题原因与解决方案

问题根源

你的输入数组中存在以换行符开头的字符串(第4、第6个元素),原函数以第一个字符串的字符为基准,第一个字符串首字符是C,但这两个字符串首字符是\n,直接不匹配,因此函数返回空字符串。此外原函数未处理空字符串和索引越界情况,鲁棒性不足。

修改后的函数

以下函数优化了鲁棒性,能正确处理包含特殊字符的数组:

def longestCommonPrefix(strs):
    # 处理空数组
    if not strs:
        return ""
    
    # 过滤数组中的空字符串
    filtered_strs = [s for s in strs if s]
    if not filtered_strs:
        return ""
    
    # 以最短字符串为基准,避免索引越界
    shortest = min(filtered_strs, key=len)
    
    for idx, char in enumerate(shortest):
        for s in filtered_strs:
            if s[idx] != char:
                return shortest[:idx]
    
    return shortest

额外说明

  1. 你之前的特殊字符替换和repr()转换完全没必要,反而会破坏原字符串结构,直接使用原数组即可。
  2. 你的输入数组中,第4、第6个字符串和其他字符串首字符完全不匹配,因此整个数组的最长公共前缀确实是空字符串。如果希望得到部分字符串的公共前缀,需要先筛选数组,比如只保留开头为Class-的字符串:
filtered = [s for s in X if s.startswith("Class-")]
print(longestCommonPrefix(filtered))

运行后会得到预期的公共前缀:Class- VII-CBSE-Mathematics\nIntegers\ne EMBIBE

内容的提问来源于stack exchange,提问作者Deshwal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:40:45