524. Longest Word in Dictionary through Deleting(med)

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.
题目描述:删除 s 中的一些字符,使得它构成字符串列表 d 中的一个字符串,找出能构成的最长字符串。如果有多个相同长度的结果,返回字典序的最小字符串。

class Solution {
    public String findLongestWord(String s, List<String> d) {
		String longest = "";
		for(String dict:d){
			int i=0;
			for(char c:s.toCharArray()){//字符串转为字符数组;;字符串直接提取字符
				if(i<dict.length()&&c == dict.charAt(i)) i++;//若等于dict中某个字符,指针移动一位
				if(i==dict.length()||i<=longest.length()){
					if(i>longest.length()||dict.compareTo(longest)<0){//两种情况,一是长度小于最长,二是字典序最小  compareTo(longest)<0  说明参数字典序小  =0 正好  >0字典序大
						longest = dict;
					}
				}
			}
		}
		return longest;
  	}
  }   
全部评论

相关推荐

零零幺零零幺:至少再做一个项目,然后猛投小厂,不然有点难
点赞 评论 收藏
分享
03-10 10:57
已编辑
门头沟学院 推荐算法
夜夜还好:我们学校说为了学生就业,更新了课程,我今天大二,上学期在学jsp,html,这学期上来工程实践,要求用springboot+vue,说什么这些技术要我们提前自己准备,要不你把学费还我吧,我给b站充个会员,人家教的比你多
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务