如何从数组中返回最长的单词?

时间:2014-03-26 18:38:10

标签: objective-c nsmutablearray

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"] 

函数应该返回单词[]中最长的单词,可以从chars []数组中的chars构造。   以上例子 - " caan" ," banc"应该退回

注意:一旦使用了chars []数组中的字符,就无法再次使用它。  eg: words[] = [ "aat" ]  characters[] = [ "a" , "t" ]   然后单词" aat"不能建造,因为我们只有1" a"在chars []。

网上有各种各样的答案,但它们不是用目标C编写的。任何人都可以帮助我在OC中解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

首先,遍历单词数组,一次一个单词,抛弃所有不能形成的单词。为此,对于每个单词,遍历单词的字符,从第二个数组中抛出该字符。如果我们来到一个不在第二个数组中的字符,则该字不能由这些字符形成。

现在我们有一个数组,其中只包含可以从这些字符组成的单词。现在按字长排序该数组,最长。现在开始走数组,查看每个单词的长度。当该长度值改变时,停止;你找到了所有最长的单词。

答案 1 :(得分:0)

// 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;  
}