通过删除在 C++ 中查找字典中最长的单词


假设我们有一个字符串和一个字符串字典,我们需要找到字典中最长的字符串,该字符串可以通过删除给定字符串的一些字符来形成。如果有多个可能的答案,则只需返回字典序最小的最长单词。如果没有结果,则返回空字符串。因此,如果输入类似于“abpcplea”并且 d = [“ale”, “apple”, “monkey”, “plea”],则结果将是“apple”。

为了解决这个问题,我们将遵循以下步骤:

  • 定义一个名为 isSubsequence() 的方法。这将接收 s1 和 s2
  • j := 0
  • 对于 i 从 0 到 s1 的大小
    • 如果 s2[j] = s1[i],则将 j 加 1
    • 如果 j = s2 的大小,则中断循环
  • 如果 j = s2 的大小,则返回 true
  • 在主方法中,执行以下操作:
  • ans := 空字符串
  • 对于 i 从 0 到 d 的大小 – 1
    • x := d[i]
    • 如果 x 的大小 > ans 的大小,或者 x 的大小 = ans 的大小并且 x < ans,则
      • 如果 isSubsequence(s, x) 为 true,则 ans := x
  • 返回 ret

让我们来看下面的实现来更好地理解:

示例

在线演示

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   bool isSubsequence(string s1, string s2){
      int j =0;
      for(int i = 0; i < s1.size(); i++){
         if(s2[j] == s1[i]){
            j++;
            if(j == s2.size()) break;
         }
      }
      return j == s2.size();
   }
   string findLongestWord(string s, vector<string>& d) {
      string ans = "";
      for(int i = 0; i < d.size(); i++){
         string x = d[i];
         if(x.size() > ans.size() || (x.size() == ans.size() && (x < ans))){
            if(isSubsequence(s, x)) ans = x;
         }
      }
      return ans;
   }
};
main(){
   vector<string> v = {"ale","apple","monkey","plea"};
   Solution ob;
   cout << (ob.findLongestWord("abpcplea", v));
}

输入

"abpcplea"
["ale","apple","monkey","plea"]

输出

apple

更新于:2020年5月2日

152 次查看

启动你的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.