LeetCode 2942.查找包含给定字符的单词
目录
题目:
题目描述:
题目链接:
思路:
思路详解:
代码:
C++代码:
Java代码:
题目:
题目描述:
题目链接:
2942. 查找包含给定字符的单词 - 力扣(LeetCode)
思路:
思路详解:
由题,words是字符串数组,我们可以遍历words字符串数组当中的每一个字符串(即words[i]),判断words[i]中是否包含字符x,如果包含则添加到答案当中
本题核心点其实就是判断words[i]中是否包含字符x,这基于不同的语言有不同的库函数写法。如果是C++,我们可以调用contains函数(包含时返回true,不包含时返回fasle);如果是Java,我们可以调用indexOf函数(包含时返回所在位置索引,不包含时返回值-1)
代码:
C++代码:
class Solution {
public:vector<int> findWordsContaining(vector<string>& words, char x) {vector<int> v;for(int i=0;i<words.size();i++){if(words[i].contains(x)){v.push_back(i);}}return v;}
};
Java代码:
class Solution {public List<Integer> findWordsContaining(String[] words, char x) {ArrayList<Integer> list=new ArrayList<>();for(int i=0;i<words.length;i++){if(words[i].indexOf(x)>=0){list.add(i);}}return list;}
}