检查两个字符串是否有两个连续的字符

时间:2016-01-09 17:45:29

标签: ruby

我需要检查两个字符串是否有两个连续的字符。

到目前为止我写了这个:

 def substring_test(str1, str2)
  return false if str1 == "" || str2 == ""
  str1.downcase.scan(/.{1,2}/).each do |pair|
     if str2.downcase.scan(/.{1,2}/).include? pair
       return true
     else 
       return false
     end
  end
end

但如果我有以下情况,它就无法运作: "首页"和" om"因为它每两个字符截断一次字符串。我可以添加什么条件,以便它适用于这些情况?我可以添加一个条件,在第一个字符之后每两个字符截断字符串,但感觉可能有更简单的方法吗?

3 个答案:

答案 0 :(得分:6)

您可以执行类似

的操作
#include <iostream>
#include <string.h>
#define INF 999999

using namespace std;

int cal(int inp);
int mem[502];
int main (void)
{
    //Gets input
    int n;
    cin >> n;

    //initialzing the array for using with memoization
    memset(mem,-1,sizeof(mem));

    //Calls the function
    //Prints the best result
    cout << cal(n) << endl;

    return 0;
}

//returns the minimum quantity of sum operations to get inp.
int cal(int inp)
{
    //Breaks recursion if it finds an answer.
    //Return cost 0. As in this stage no processing was done.
    if(!inp)
        return 0;

    // Returning infinite cost for invalid case.
    if(inp < 0)
        return INF;

    int _ret = mem[inp];

    // If already visited here before then no need to calcuate again.
    // Just return previous calculation. This is called memoisation.
    // If not visited then _ret would have equal to -1.
    if(_ret >=0 )
        return _ret;

    _ret = INF;

    //Tries every combination and takes the minimum cost.
    _ret = min(_ret, cal(inp-13)+1);
    _ret = min(_ret,cal(inp-6)+1);
    _ret = min(_ret,cal(inp-2)+1);
    _ret = min(_ret,cal(inp-1)+1);

    // Updating the value so that can be used for memoization.
    mem[inp] = _ret;

    return _ret;
}

使用def substring_test(str1, str2) str1.each_char.each_cons(2).any? { |pair| str2.include? (pair.join) } end 方法会在找到第一个匹配后立即退出循环。

答案 1 :(得分:4)

这是我的变体:

def split_by_2_chars(string)
  (0..string.size - 2).map { |i| string[i..i + 1].downcase }
end

def substring_test(s1, s2)
  (split_by_2_chars(s1) & split_by_2_chars(s2)).any?
end

puts substring_test("Home", "om")   #=> true
puts substring_test("Abcd", "defg") #=> false

答案 2 :(得分:2)

这是一种方法。使用Enumerable#any?有助于我们将循环迭代次数保持在最小值,因为一旦找到匹配就会立即退出。

s1 = "Home"
s2 = "Rome"

s1.downcase.split('').each_cons(2).any? do |c1|
    s2.downcase.split('').each_cons(2).any?{|c2| c2 == c1}
end
#=> true