leetcode题目
30.串联所有单词的子串
1.题目描述
给定一个字符串 s 和一些长度相同的单词 words 。找出 s 中恰好可以由 words 中所有单词串联形成的子串的起始位置。
注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
1.1示例
示例1:
示例2:
2.代码
分析:这道题是参考了大佬的方法,滑动窗口法。链接: https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/solution/chuan-lian-suo-you-dan-ci-de-zi-chuan-by-powcai/.
class Solution {
private List<Integer> res;
HashMap<String,Integer> map;
HashMap<String,Integer> tmp;
public List<Integer> findSubstring(String s, String[] words) {
res=new ArrayList<>();
map=new HashMap<>();
tmp=new HashMap<>();
if(s==null || s.length()==0){
return res;
}
if(words==null || words.length==0){
return res;
}
for(int i=0;i<words.length;i++){
map.put(words[i],map.getOrDefault(words[i],0)+1);
}
int one_word=words[0].length();
int n=words.length;
if(s.length()<one_word*n){
return res;
}
for(int i=0;i<one_word;i++){
int l=i;
int r=i;
int count=0;
tmp.clear();
while(r+one_word<=s.length()){
String ss=s.substring(r,r+one_word);
r +=one_word;
if(!map.containsKey(ss)){
count=0;
l=r;
tmp.clear();
}else{
tmp.put(ss,tmp.getOrDefault(ss,0)+1);
count++;
while(tmp.getOrDefault(ss,0)>map.getOrDefault(ss,0)){
String ts=s.substring(l,l+one_word);
count--;
tmp.put(ts,tmp.getOrDefault(ts,0)-1);
l +=one_word;
}
if(count==n){
res.add(l);
}
}
}
}
return res;
}
}
58.最后一个单词的长度
1.题目描述
给定一个仅包含大小写字母和空格 ’ '的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指仅有字母组成、不包含任何空格字符的 最大子字符串。
1.1示例
2.代码
分析:从字符串 s 的末尾开始向前遍历。如果碰到空格’,就继续向前遍历。若当前的单词仅由字母组成,且碰到空格时,就输出当前字符的长度。
class Solution {
public int lengthOfLastWord(String s) {
//判断s的非空性
if(s==null || s.length()==0){
return 0;
}
//记录当前单词的长度
int ans=0;
//标记末尾为起始位置
int end=s.length()-1;
//找到符合条件的单词的末位置
while(end>=0 && s.charAt(end)==' '){
end--;
}
//判断该字符创是否全为空格
if(end<0){
return 0;
}
//找到单词的起始位置,并记录单词长度
while(end>=0 && s.charAt(end)!=' '){
end--;
ans++;
}
//返回最后一个单词的长度
return ans;
}
}
第一题链接: https://leetcode-cn.com/problems/substring-with-concatenation-of-all-words/.
第二题链接: https://leetcode-cn.com/problems/length-of-last-word/.