簡體   English   中英

字符串順序(從左到右,從右到左)

[英]strings order (left to right and right to left)

試圖了解我們如何確定第二個字符串(S2)是否遵循與第一個字符串(s1)相同的字母順序(無論它是從左到右還是從右到左):

例子:

  1.  qwer asdf Answer:No
  2.  abcdefghi dfge Answer: No
  3.  qwkedlrfid kelid Answer: Yes
  4.  abcdefghi hcba Answer: Yes
  5.  abacdfeag bca Answer:Yes (based on the last 'a' in the first string)

有助於將結果過濾為“否”的一件事是,如果 string2 中的項目在 string1 中不存在,則自動為“否”..exp 1)

我的代碼沒有完成並且顯然沒有返回正確的答案,但是由於社區通常希望看到一些努力來分享我迄今為止所擁有的......並且不知道如何繼續......

s1=input()
s2=input()

check=any(items in s1 for items in s2)
if check is not True or s1[-1] >= s2[0]:
 print("NO")
elif s2[-1] <= s1[0]:
 print("YES")

這是一個沒有正則表達式但字符串切片和str.find的版本:

def check(s1, s2):
    i = 0
    for c in s2:  # looping over the characters in s2
        if i < len(s1):
            incr = s1[i:].find(c) + 1  # looking for c in the rest of s1
            if incr == 0:  # c not found
                break
            i += incr
        else:  # end of s1 reached, but still c's to cover
            break
    else:  # loop went through without break -> found
        return True
    return False  # loop exit with break -> not found

def check_contains(s1, s2):
    return check(s1, s2) or check(s1[::-1], s2)

你的例子:

strings = [("qwer", "asdf"), ("abcdefghi", "dfge"), ("qwkedlrfid", "kelid"), ("abcdefghi", "hcba"), ("abacdfeag", "bca")]
for s1, s2 in strings:
    print(check_contains(s1, s2))

結果:

False
False
True
True
True

我對性能測量進行了一些嘗試:在我看來,Bharel 的版本在您提供的那種字符串方面比這個版本更有優勢。 當要搜索的字符串變大時,這似乎會改變。 我嘗試了以下方法( check_contains_1是 Bharel 的解決方案, check_contains_2是此答案中的解決方案):

from random import choices, randint
from string import ascii_lowercase as chars
from time import perf_counter

num = 10_000
max_len_1, max_len_2 = 50, 5
strings = [
    (
        "".join(choices(chars, k=randint(2, max_len_1))),
        "".join(choices(chars, k=randint(2, max_len_2)))
    )
    for _ in range(num)
]

start = perf_counter()
result_1 = [check_contains_1(s1, s2) for s1, s2 in strings]
end = perf_counter()
print(f"Version 1: {end - start:.2f} secs")

start = perf_counter()
result_2 = [check_contains_2(s1, s2) for s1, s2 in strings]
end = perf_counter()
print(f"Version 2: {end - start:.2f} secs")

print(result_1 == result_2)

Output:

Version 1: 1.85 secs
Version 2: 0.04 secs
True

但也許我犯了一個錯誤...

您可以自己實現基於堆棧的回溯機制,或者對每個字母遞歸地執行。

我只是選擇讓 Python 的正則表達式引擎完成這項工作:

import re

def check_contains(s1, s2):
    regex = f"(?:{'.*'.join(s2)}|{'.*'.join(reversed(s2))})"
    return bool(re.search(regex,s1))

我基本上創建了一個正則表達式來搜索每個字母之間的任何內容,並且相同的反轉。

我懷疑是否有更好的解決方案。 您必須處理如此多的邊緣情況,以至於 O(n^n) 是必須的。 如果其他人有更好的想法,歡迎您加入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM