字符串中出现子序列

编程入门 行业动态 更新时间:2024-10-14 00:27:37
本文介绍了字符串中出现子序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

给出2个类似bangalore和blr的字符串,返回一个字符串是否显示为另一个字符串的子序列。上面的情况返回true,而bangalore和brl返回false。

Given 2 strings like bangalore and blr, return whether one appears as a subsequence of the other. The above case returns true whereas bangalore and brl returns false.

推荐答案

贪婪策略应该可以解决此问题。

Greedy strategy should work for this problem.

  • 在大字符串(* b * angalore)中查找可疑子字符串(blr)的首字母
  • 查找第二个字母从第一个字母的索引加一个(anga * l * ore)开始
  • 查找第二个字母,从第二个字母的索引加一个(o * r * e)
  • 继续,直到您不再在字符串中找到下一个blr字母(不匹配),或者子序列中的字母用完(您有匹配项)为止。 / li>
  • Find the first letter of the suspected substring (blr) in the big string (*b*angalore)
  • Find the second letter starting at the index of the first letter plus one (anga*l*ore)
  • Find the third letter starting at the index of the second letter plus one (o*r*e)
  • Continue until you can no longer find the next letter of blr in the string (no match), or you run out of letters in the subsequence (you have a match).

以下是C ++中的示例代码:

Here is a sample code in C++:

#include <iostream> #include <string> using namespace std; int main() { string txt = "quick brown fox jumps over the lazy dog"; string s = "brownfoxzdog"; int pos = -1; bool ok = true; for (int i = 0 ; ok && i != s.size() ; i++) { ok = (pos = txt.find(s[i], pos+1)) != string::npos; } cerr << (ok ? "Found" : "Not found") << endl; return 0; }

更多推荐

字符串中出现子序列

本文发布于:2023-11-30 07:12:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649131.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   序列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!