简体   繁体   中英

I need to text a first word with the greatest number of different letters. How can i do it?

For example: I have a string: "abcdef aaaaaaa bbbbbb" and program should output "abcdef" I don't know how to do it

#include <iostream>
#include <string>
#include <fstream>

using namespace std;
void main()
{
    string a;
    int count = 0;
    getline(cin, a);
    for (int i = 0; i < a.length(); i++) {
        if (a[i] == ' ') {
            count++;
        }
    }
    cout << count+1;
}

Yeah we can do this.. Following is the code which can help you out.

#include<bits/stdc++.h>

using namespace std;

int main(){
string s;
getline(cin,s);
s=s+' ';
string word="";
int ans=0;
map<int,string> mp;
for(int i=0;i<s.length();i++){
    char ch=s[i];
    if(s[i]!=' ')
        word=word+ch;
    else{
        int c=0;
        for(int j=0;j<word.length()-1;j++){
            if(word[j]!=word[j+1])
                c++;
        }
        ans=max(ans,c);
        mp[c]=word;
        word="";
    }
}
cout<<mp[ans];

}

I think the easiest way to do it is to use std::stringstream to split your string into words.

After that, as already suggested in comments, you could use std::set to count the letters numbers since each element in std::set is unique.

A possible solution would be:

std::pair<std::string, unsigned int> max_letters_word(const std::string & s)
{
    std::pair<std::string, unsigned int> result {"", 0};

    std::stringstream ss(s);
    std::string word;
    std::set<char> set;

    while(ss >> word)
    {
        for(char c : word)
            set.insert(c);

        if(set.size() > result.second)
        {
            result.first = word;
            result.second = set.size();
        }
        set.clear();
    }

    return result;
} 

And you could use this function as follows:

int main()
{
    // Considering this string
    std::string s = "abcdef aaaaaaaaa bbbuubbb";

    // Call max_letters_word()
    std::pair<std::string, unsigned int> result = max_letters_word(s);
    
    // Display the result
    std::cout << result.first << ": " << result.second << '\n';

    return 0;
}

Live example

With any programming language, "How can I do x ?" can have a lot of different answers. Some languages, like python try to lull into the idea that there is one correct (or pythonic as they say) way of doing things, but it's still not true. To python's credit, they usually have a lot less variation than C++ can have.

That is to say, it's a bad question. You need to let us know what your requirements and restrictions are. That allows people to provide solutions that can actually work for you.

Break down the task into sub-tasks. Break the sub-tasks down. Figure out what your algorithm is before writing any code. At a high level, it looks like you need to:

  • Split the line into individual words
  • Count the unique characters in each word
    • Keep track while counting to know which word has the most unique characters
  • Print the word with the most unique characters

You need to break those tasks down further until you arrive at something you can do. Then do it, and move on. Eventually you'll have a complete program.

If I were to guess, this solution is probably not what you're looking for:

#include <algorithm>
#include <cctype>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

std::size_t count_unique_chars(std::string word) {
  for (auto& i : word) {
    i = std::toupper(i);
  }

  std::sort(word.begin(), word.end());
  word.erase(std::unique(word.begin(), word.end()), word.end());

  return word.length();
}

int main(int argc, char* argv[]) {
  if (argc != 2) return 1;

  std::string stringLine = argv[1];
  std::stringstream stream(stringLine);
  std::vector<std::string> words;

  std::copy(std::istream_iterator<std::string>(stream),
            std::istream_iterator<std::string>(), std::back_inserter(words));

  int maxUniqueChars = 0;
  std::string wordWithMostUniqueChars;
  for (auto i : words) {
    int charCount = count_unique_chars(i);
    if (charCount > maxUniqueChars) {
      maxUniqueChars = charCount;
      wordWithMostUniqueChars = i;
    }
  }

  std::cout << wordWithMostUniqueChars << '\n';
}

Outputs:

❯ ./a.out "abcdef aaaaaaa bbbbbb"
abcdef

❯ ./a.out "cat cattttttt cats"
cats

It works, but this looks like a homework problem and most of that code probably flies right over your head. So it doesn't really help you.

I can make some assumptions, but even they might be off. I'm just trying to highlight how much work goes into asking the right questions. It may sound super-annoying, but there are nothing but benefits. Formulating a "good" question requires you to put in effort. That effort comes across in the asking, and when people get a well-formulated question, they will recognize your effort and be more willing to help. It's also easier to answer a well formulated question.

Here's another program that uses a different tactic.

#include <cctype>
#include <iostream>
#include <string>
#include <vector>

std::size_t count_unique_chars(std::string word) {
  std::vector<char> letters(26, 0);

  for (auto i : word) {
    char c = std::toupper(i);
    ++letters[c - 'A'];
  }

  int count = 0;
  for (auto i : letters) {
    if (i > 0) ++count;
  }

  return count;
}

int main(int argc, char* argv[]) {
  if (argc != 2) return 1;

  std::string stringLine = argv[1];
  std::vector<std::string> words;

  while (stringLine.size() > 0) {
    std::size_t idx = stringLine.find_last_of(" ");
    std::string word = stringLine.substr(idx + 1);
    words.push_back(word);
    if (idx == std::string::npos) idx = 0;
    stringLine.erase(idx);
  }

  std::size_t maxUniqueChars = 0;
  std::string wordWithMostUniqueChars;
  for (auto i : words) {
    std::size_t count = count_unique_chars(i);
    if (count > maxUniqueChars) {
      maxUniqueChars = count;
      wordWithMostUniqueChars = i;
    }
  }

  std::cout << wordWithMostUniqueChars << '\n';
}

It still relies on taking advantage of std::string and what it offers, which might not fit with your restrictions.

Both programs follow the high-level steps outlined above. Both programs work, but go about executing the algorithm in different ways. Having clear requirements, and knowing what restrictions are in place will also steer you toward a solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM