相似字符串

今天遇到了一個算法題目:相似字符串。題目提出了一個相似字符串的定義:形如“aba”與“xyx”相似;“abc”與“xyz”相似,要求找出輸入的兩個字符串中相似字符串的個數。這裏寫圖片描述

首先我感覺這個有點類似於正則表達式,但需要根據給定的規則匹配出所有的字符串,又有點像KMP算法的過程。
這裏給出一個思路:
在“最長公共字符串”這個DP問題中,用了一個矩陣來保存字符比較的狀態,但在這個問題中,“aba”與“xyx”沒法直接比較,所以我們需要提取它們的共同特徵來比較,比如都轉化成“0,1,0”的數字就可以直接比較了。

這裏給出Python3的實現代碼:

#!/bin/python
# -*- coding: utf8 -*-
import sys
import os
import re

#請完成下面這個函數,實現題目要求的功能
#當然,你也可以不按照下面這個模板來作答,完全按照自己的想法來 ^-^ 
#******************************開始寫代碼******************************
def str_info(data):
    res = []
    res_str = []
    for i  in range(0,len(data)):
        if data[i]  not in res_str:
            res_str.append(data[i])
            res.append(i)
        else:
            res_str.append(data[i])
            res.append(data.index(data[i]))

    return res

def  solve(S, T):
    t_res = str_info(T)

    count = 0

    for i in range(0,len(S)-len(T)+1):
        combine = S[i:i+len(T)]
        s_res = str_info(combine)
        if s_res == t_res:
            count +=1

    return count


#******************************結束寫代碼******************************

'''
try:
    _S = input()
except:
    _S = None

try:
    _T = input()
except:
    _T = None
'''

# res = solve(_S, _T)
res = solve("ababcb", "xyx")


print(str(res) + "\n")

假設len(string1) = M, len(string2) = N,這個方法的時間複雜度爲O(M*N)。
還有一些方法:

作者:上天請賜我一個OFFER
鏈接:https://www.nowcoder.com/discuss/106200?type=0&order=0&pos=40&page=1
來源:牛客網

def solve(S, T):
    if not S or not T:
        return 0
    if len(S) < len(T):
        return 0
    count = 0
    for i in range(len(S) - len(T) + 1):
        if isSomorphic(S[i:i+len(T)], T):
            count += 1
    return count

def isSomorphic(S, T):
    return len(set(S)) == len(set(T)) == len(set(zip(S, T)))

http://discuss.acmcoder.com/topic/5b9518c67275c3490031a4c6

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章