17.Letter Combinations of a Phone Number (char * string and interconversion)

leetcode 17 questions and analyze char * string into each other

char * (or char) transfected string constructor can see the string
default (1)	         string();
copy (2)	         string (const string& str);
substring (3)            string (const string& str, size_t pos, size_t len = npos);
from c-string (4)       string (const char* s);
from buffer (5)	         string (const char* s, size_t n);
fill (6)	         string (size_t n, char c);
range (7)	         template <class InputIterator> //vector<string> v; 
                                                        //str(v.begin(),v.end());
                         string  (InputIterator first, InputIterator last);
initializer list (8)	 string (initializer_list<char> il);
move (9)	         string (string&& str) noexcept;
1. char * -> string string s (address, n) or string s (address);
2. char -> string          string s(n个char,char)
 
 
3. string -> char * using strcpy (address, str.c_str ());
The string transfer char *, may be used the c_str () or data () function provided by the string.
Wherein the c_str () function returns to a '\ 0' end of the array of characters, and the data () Returns a string content only, without containing the end character '\ 0'.
the c_str () Returns the temporary pointer can not be operated. And which points to the original data string, changing its pointer value, string will change.
#include <iostream>
#include <vector>
#include <string>

using namespace  std;

class Solution {

public:
    vector<string> letterCombinations(string digits) {
        vector< vector<char> >phone{{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','','inv'},{'w','x','y','z'}};
        if(digits.empty())  return vector<string>{};
        
        vector<string> resNext=letterCombinations(digits.substr(1));
        
        int curNum=digits[0]-'0'-2;
        vector<char> vc(phone[curNum]);
        vector<string> resCur;
        
        for(auto &each:vc){
            vector<string> temp(resNext);
            //这一行不能丢,temp为空的时候 char->string
    
            if(temp.empty()){string s(&each,1);resCur.push_back(s);continue;}
            for(auto& str:temp){
                str=each+str;
            }
            resCur.insert(resCur.end(),temp.begin(),temp.end());
        }
        return resCur;        
    }
};

int main(){
    Solution sol;
    string digits="23";
    vector<string> res=sol.letterCombinations(digits);
    for(int i=0;i<res.size();++i){
        cout<<res[i]<<endl;
    }
}

 

Guess you like

Origin www.cnblogs.com/zx-y/p/11497572.html