Inscription LeetCodeGOGOGO brush 03-- code optimization (using strings stream and c ++ 11 new features to handle strings)

819. Most Common Word

Difficulty:

Medium

Ideas:

String processing problems, precludes part of the word, the word library consisting of (banned), asked to identify the most non-banned word appears in an article (not case sensitive).

This problem is also very clear idea of, first of all deal with the article, processed into a single word, and all converted to lowercase, followed by the insertion unordered_map, the final traverse the map to get results

In fact, the difficulty of this question is not, however, conventional code is not simple, eloquent accidentally came down fifty or sixty lines

Code:

/*
Author Owen_Q
*/

class Solution {
public:
    string mostCommonWord(string paragraph, vector<string>& banned) {
        re.clear();
        int st = 0;
        int plen = paragraph.size();
        while(st<plen)
        {
            if(ischa(st,paragraph))
            {
                int pos = 0;
                string words = "";
                for(;st+pos<plen;pos++)
                {
                    if(ischa(st+pos,paragraph))
                    {
                        if(isupcha(st+pos,paragraph))
                            paragraph[st+pos] += 'a'-'A';
                        words += paragraph[st+pos];
                    }
                    else
                        break;
                }
                if(find(banned.begin(),banned.end(),words)==banned.end())
                {
                    re[words]++;
                    //cout << words <<endl;
                }
                st += pos+1;
            }
            else
                st++;
        }
        
        string rewords;
        int renum = 0;
        for(auto it=re.begin();it!=re.end();it++)
        {
            if((*it).second>renum)
            {
                renum = (*it).second;
                rewords = (*it).first;
            }
        }
        return rewords;
    }
private:
    unordered_map<string,int> re;
    
    bool ischa(int a, string paragraph)
        {
            if((paragraph[a]>='a'&&paragraph[a]<='z')||(paragraph[a]>='A'&&paragraph[a]<='Z'))
                return true;
            else
                return false;
        }
    
    bool isupcha(int a, string paragraph)
        {
            if(paragraph[a]>='A'&&paragraph[a]<='Z')
                return true;
            else
                return false;
        }
    
};

So Let's look at the optimized code

 

Strings and string handling functions stream Review:

istringstream:

istringstream(string str)

New features string stream is not c ++ 11, but it really is a very easily overlooked but very useful feature

The stream space as separator character string, a full character string may be divided into a plurality of smaller strings, similar to a standard input stream as the partition so that the string has become very easy, without having to think as the original character by a string element within a manually separated

ctype.h:

ctype.h the library function does have a lot of very clever function, although it is not difficult to implement, but can make full use of these functions the code becomes very simple

There are these common functions:

the isalpha () determined character is a letter (case)

scanned using the ISNUM () determines whether the number of characters;

ispunct () determines whether the character is the special symbol

islower () determines whether the character lowercase

isupper () to determine if a character is a capital letter

tolower () converts uppercase letters to lowercase letters

toupper () converts lowercase to uppercase

c ++ 11 Knowledge Review:

auto:

Automatically determine the type, in fact, this feature is very simple, the main variable is not defined in their own type, but the compiler can automatically determine based on the value passed in variable. The main benefit of this feature is reflected in the simplicity long variable declarations, such as iterator declaration, the use of auto you can omit the lengthy iterator declaration makes the code becomes very clear and concise

for:

for(declaration:expression)

c ++ 11 also for the cycle has been upgraded, but the most primitive for (;;) use, is now also available in a for loop in python similar to the usage. This makes the array traversal has become, especially string manipulation becomes very convenient

Note that if you want to change the value of the declaration, remember that adding a reference symbol

Code upgrade:

The first is a string process for using the new features will all uppercase to lowercase processing, processing all non-alphanumeric character string into a space to separate the stream

Then translated into strings stream is processed, for each word unordered_map still thrown in, and were determined once every incoming process, to leave a uniform final determination code

Simple two-step to complete the entire code becomes very clear and beautiful

Code:

/*
Author Owen_Q
*/

class Solution {
public:
    string mostCommonWord(string paragraph, vector<string>& banned) {
        for(auto &c: paragraph)
            c = isalpha(c)? tolower(c): ' ';
        istringstream iss(paragraph);
        string words, rewords;
        int renum = 0;
        re.clear();
        while(iss >> words)
        {
            if(find(banned.begin(),banned.end(),words)==banned.end())
            {
                re[words]++;
                if(re[words]>renum)
                {
                    renum = re[words];
                    rewords = words;
                }
            }
        }
        return rewords;
    }
private:
    unordered_map<string,int> re;
};

 

Published 97 original articles · won praise 89 · views 20000 +

Guess you like

Origin blog.csdn.net/Owen_Q/article/details/104035089