[LeetCode] Longest Word in Dictionary through Deleting

声明:原题目转载自LeetCode,解答部分为原创

Problem :

Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.

Example 1:

Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

Output: 
"apple"

Example 2:

Input:
s = "abpcplea", d = ["a","b","c"]

Output: 
"a"

Solution:

        思路:先将vector容器中“能够通过删减给定字符串s的某些字母而得到的字符串”存到sub_set容器中,再对sub_set容器存放的字符串进行排序,然后输出头元素。根据题意,需要重新定义cmp()比较函数,当字符串a、b满足a.size() = b.size()时,将字典序小的放在前;否则,将size()大的字符串放在前。

        代码如下:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

bool cmp(string a, string b)
{
	if(a.size() == b.size())
		return a < b;
	else if(a.size() > b.size())
		return true;
	else
		return false;
}

class Solution {
public:
    string findLongestWord(string s, vector<string>& d) {
        vector<string> sub_set;
        for(int i = 0 ; i < d.size() ; i ++)
        {
        	if(valid_s(s, d[i]))
        		sub_set.push_back(d[i]);
		}
		
		if(!sub_set.empty())
		{
			sort(sub_set.begin(), sub_set.end(), cmp);
			return sub_set.front();
		}
		else
			return "";
    }
    
private:
	bool valid_s(string sub, string d) {
		int point_0 = 0;
		int point_1 = 0;
		while(point_1 < d.size() && point_0 < sub.size())
		{
			if(d[point_1] == sub[point_0])
			{
				point_0 ++;
				point_1 ++;
			}
			else
			{
				point_0 ++;
			}
		}
		
		if(point_1 == d.size())
			return true;
		else
			return false;
	}
};

int main()
{
	vector<string> text_1;
	vector<string> text_2;
	
	text_1.push_back("abpcplea");
	text_2.push_back("plea");
	text_2.push_back("ale");
	text_2.push_back("apple");
	text_2.push_back("monkey");
	
	Solution text;
	cout << text.findLongestWord(text_1.front(), text_2) << endl;

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值