假設
str = "???!!!???!"
如果我們首先刪除兩組"???"
我們留下"!!!!"
,不能被進一步減小。
如果我們第一次刪除組"!!!"
我們剩下"??????!"
,這是不能進一步減少。
如果我們被允許移除任何一個字符的所有奇怪羣體,而沒有提到另一個字符的效果,我們獲得!
,這不能進一步減少。
目前還不清楚使用什麼規則。這裏有三個可能性和代碼來實現每個。
我將使用以下兩個正則表達式,並在前兩種情況下使用一個輔助方法。
Rq =/
(?<!\?) # do not match a question mark, negative lookbehind
\? # match a question mark
(\?{2})+ # match two question marks one or more times
(?!\?) # do not match a question mark, negative lookahead
/x # free-spacing regex definition mode
它通常寫成。
同樣,
Rx = /(?<!!)!(!{2})+(?!!)/
def sequential(str, first_regex, second_regex)
s = str.dup
loop do
size = s.size
s = s.gsub(first_regex,'').gsub(second_regex,'')
return s if s.size == size
end
end
予應用的每個的三種方法的以下兩個示例字符串:
str1 = "???!!!???!"
str2 = 50.times.map { ['?', '!'].sample }.join
#=> "?!!!?!!!?!??????!!!?!!??!!???!?!????!?!!!?!?!???!?"
替換"?"
的"!"
然後奇數羣組的所有奇數組然後重複直到沒有進一步的清除是可能的
def question_before_exclamation(str)
sequential(str, Rq, Rx)
end
question_before_exclamation str1 #=> "!!!!"
question_before_exclamation str2 #=> "??!??!?!!?!?!!?"
更換"!"
的"?"
然後奇組的所有奇數組,然後重複,直到沒有進一步的清除有可能
def exclamation_before_question(str)
sequential(str, Rx, Rq)
end
exclamation_before_question str1 #=> "??????!"
exclamation_before_question str2 #=> "??!????!!?!?!!?!?!!?"
更換兩個"?"
和"!"
的所有奇數組再重複,直到沒有進一步的清除有可能
Rqx = /#{Rq}|#{Rx}/
#=> /(?-mix:(?<!\?)\?(\?{2})+(?!\?))|(?-mix:(?<!!)!(!{2})+(?!!))/
def question_and_explanation(str)
s = str.dup
loop do
size = s.size
s = s.gsub(Rqx,'')
return s if s.size == size
end
end
question_and_explanation str1 #=> "!"
question_and_explanation str2 #=> "??!?!!?!?!!?!?!!?"
你對你的問題有足夠的重視,欣賞給定的時間。 –