Objective c 如何从数组中返回最长的单词?
函数应返回words[]中最长的单词,该单词可由chars[]数组中的chars构造。 对于上述示例,应返回“caan”、“banc” 注意:一旦使用chars[]数组中的字符,就不能再使用它。Objective c 如何从数组中返回最长的单词?,objective-c,nsmutablearray,Objective C,Nsmutablearray,函数应返回words[]中最长的单词,该单词可由chars[]数组中的chars构造。 对于上述示例,应返回“caan”、“banc” 注意:一旦使用chars[]数组中的字符,就不能再使用它。 eg:words[]=[“aat”] 字符[]=[“a”,“t”] 那么单词“aat”就不能被构造,因为我们在chars[]中只有1个“a” 网上有各种答案,但它们不是用目标C写的。有人能帮我在OC中解决这个问题吗?首先,遍历单词数组,一次一个单词,扔掉所有无法从第二个数组中形成的单词。为此,对于每个单
eg:words[]=[“aat”]
字符[]=[“a”,“t”]
那么单词“aat”就不能被构造,因为我们在chars[]中只有1个“a”
网上有各种答案,但它们不是用目标C写的。有人能帮我在OC中解决这个问题吗?首先,遍历单词数组,一次一个单词,扔掉所有无法从第二个数组中形成的单词。为此,对于每个单词,遍历单词的字符,从第二个数组中抛出该字符。如果我们找到一个不在第二个数组中的字符,那么这个单词就不能由这些字符组成 现在我们有了一个数组,它完全由这些字符组成的单词组成。现在按字长对数组排序,最长优先。现在开始遍历数组,查看每个单词的长度。当长度值改变时,停止;你已经发现了所有最长的单词。 <代码> //程序在C++中做同样的事情。
given 2 arrays wrds[] , chars[] as an input to a function such that
wrds[] = [ "abc" , "baa" , "caan" , "an" , "banc" ]
chars[] = [ "a" , "a" , "n" , "c" , "b"]
#包括
#包括
#包括
#包括
使用名称空间std;
使用std::vector;
向量匹配(字符**字、整数大小、字符*字符、映射和秒)
{
向量res;
std::map mapi=秒;
int currsize=0;
对于(int i=0;i这不是家庭作业。这是我在一个网站上看到的苹果访谈中的一个问题。很有趣。我可以很容易地找到wrds[]中最长的单词。但我不知道如何确保这些单词是为chars[]构建的。“网上有各种anwers,但它们不是用C写的。”-当您尝试实现这些在Objective-C中使用的算法时,遇到了什么问题?请注意,您给出的数组是C字符串的C数组,因此C解决方案直接适用于“Objective-C”解决方案。您不也应该检查单词中的重复字符以删除这些字符吗?
// Program do to do the same in C++
#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
using std::vector;
vector<char*> match(char** words, int size, char* chars, map<char,int> &second)
{
vector<char*> res;
std::map<char,int> mapi = second;
int currsize = 0;
for(int i = 0; i < size ; i++){
char* wo;
wo = words[i];
int s= 0;
for( s=0; wo[s] != '\0'; s++){
}
if(s < currsize) {
//No need to iterate if already found a bigger word
//continue to see if the next word if bigger of the same size as currsize
continue;
}
// iterate through the map to see if all the letters present in the first array
bool found = true;
for(int j = 0; j <s ; j++){
map<char, int>::iterator it = mapi.find(wo[j]);
if(it == mapi.end()) {
found= false;
break;
}
}
if(!found) {
continue;
}
if(s > currsize) {
//remove the past res as found a bigger one
res.clear();
}
//Store this word in the vector as it is one of the biggest word so far
res.push_back(wo);
currsize = s;
}
return res;
}
int main()
{
map<char, int> leters;
char* words[5] = {"adc", "baa", "caan", "daanns", "banc"};
char ch1[]= {'a', 'a', 'n', 'c', 'b'};
int chsize = sizeof(ch1);
// put the ch1 chars in a map
for(int i = 0; i < chsize; i++) {
map<char,int>::iterator it =leters.find(ch1[i]);
if(it != leters.end()) {
it->second = it->second+1;
} else {
leters.insert(make_pair(ch1[i], 1));
}
}
char* chars = ch1;
vector<char*>v = match(words, 5, ch1, leters);
for(vector<char*>::iterator it = v.begin(); it != v.end(); it++) {
// it will print the result
cout << *it << endl;
}
return 0;
}