0 Introduction
Usually used in the process of brushing questions, there are many problems about character conversion. A comprehensive summary is made here in order to quickly solve and solve the problem in this way.
0.1 string and int convert to each other
0.1.1 converting string type to int type
Method 1: use the atoi () function
#include<bits/stdc++.h> using namespace std; int main(){ string str="123"; cout<<str<<" str The type of is"<<typeid(str).name()<<endl;//The output Ss represents the string type //The parameter type of atoi is (const char *nptr) and string is a class, so you need to get the first address of STR, that is, str.c_str() int num=atoi(str.c_str()); cout<<num<<" num The type of is"<<typeid(num).name()<<endl;//The output i represents the int type }
1
The output of typeid(num).name() of devc + + is i, and the output of vs2017 is int. the output of this function may be different from that of different compilers.
There are also similar functions:
long atol(const char *nptr); Converts a string to a long integer
double atof(const char *nptr); Convert string to floating point number
long int strtol(const char *str, char **endptr, int base); Convert the string pointed to by the parameter STR to a long integer according to the given base
Method 2: convert through stringstream class
#include<bits/stdc++.h> using namespace std; int main() { stringstream sstream; string str="123"; int num; cout<<"str="<<str<<" str The type of is"<<typeid(str).name()<<endl;//The output Ss represents the string type sstream<<str;// Puts a value of type string into a string stream sstream>>num;//Output the first data in s sstream to num cout<<"num="<<num<<" num The type of is"<<typeid(num).name()<<endl;//The output i represents the int type }
0.1.2 converting int type to string type
Method 1: use to_string() function
#include<bits/stdc++.h> using namespace std; int main() { int num=123; string str=to_string(num); cout<<"num="<<num<<" num The type of is"<<typeid(num).name()<<endl;//The output i represents the int type cout<<"str="<<str<<" str The type of is"<<typeid(str).name()<<endl;//The output Ss represents the string type }
to_ The string (x) function has multiple overloads, as long as X is a built-in numeric type.
Method 2: convert through stringstream class
#include<bits/stdc++.h> using namespace std; int main() { stringstream sstream; string str; int num=123; cout<<"num="<<num<<" num The type of is"<<typeid(num).name()<<endl;//The output i represents the int type sstream<<num;// Puts a value of type num into a string stream sstream>>str;//Output the first data in s sstream to str cout<<"str="<<str<<" str The type of is"<<typeid(str).name()<<endl;//The output Ss represents the string type }
Method 3: use the itoa () function
Function prototype: char * Itoa (int value, char * string, int radius);
The first parameter is the number to convert
The second parameter is the target string (character array) to write the conversion result
The third parameter is the radix (base) used to transfer numbers ⭐ (can be used for binary conversion)
Return value: pointer to string
#include<bits/stdc++.h> using namespace std; int main() { int num=123; char strc[100]; string str=itoa(num,strc,10);//The returned pointer is the pointer to strc, which can be directly stored in the string type cout<<"num="<<num<<" num The type of is"<<typeid(num).name()<<endl;//The output i represents the int type cout<<"str="<<str<<" str The type of is"<<typeid(str).name()<<endl;//The output Ss represents the string type }
Other similar functions:
litoa() converts a long integer value to a string
ultoa() converts an unsigned long integer value to a string
0.2 split implementation (stringstream+getline Implementation)
vector<string> split(string str, char del) { stringstream ss(str); string temp; vector<string> ret; while (getline(ss, temp, del)) { ret.push_back(temp); } return ret; }
0.3 Note the conversion of string char* char []
Convert string to char *:
If you want to convert string directly to const char * type, string has two functions to use.
One is. c_str(), and the other is. data member function.
Examples are as follows:
string s1 = "abcde"; const char *k = s1.c_str(); const char *t = s1.data(); printf("k:[%s] t:[%s]\n", k, t); system("pause");
0.4 delete specified characters in string
Use the string::iterator (string iterator) to iterate from the beginning str.begin() to the end str.end(), and then use the string.erase(const_iterator p) function to delete the character pointed to by the iterator.
#include <iostream> #include <string> using namespace std; int main() { string str; char ch; cin >> str; cin >> ch; string::iterator it; for (it = str.begin(); it < str.end(); it++) { if (*it == ch) { str.erase(it); it--; /* it--This is important because after erase() is used to delete the character pointed to by it, the following character will move over, it The position pointed to is filled with the last character, and the it + + at the end of the for statement moves it backward A position is omitted, so the filled character is ignored. Add it -- here and for Statement is offset by it + +, enabling the iterator to access all characters. */ } } cout << str; return 0; }
0.5 char & int convert to each other
Convert ASCII numbers to char, see 1.3 of this section
(char)( (ch - 'A' + up_char_offset + 26) % 26 + 65)
1.ASCII method
Recommendation: 5 stars ★★★★
This is the most versatile method and relatively simple. The disadvantage is that you can only convert one by one
code:
char cNum='5',result1; int iNum=5,result2; //char to num result2=cNum-48; //num to char result1=iNum+48;
In short, int to char is + 48
char to int is - 48
2. Function method
Recommendation: 3 stars ★★★
Use itoa and atoi (both in the stdlib.h header file) functions to convert
The operation is simple and can be converted at one time (not one by one), but there is a big problem: the itoa function is not the implementation of standard C and can only be compiled under windows. In other words, if you write software, it is no problem. But if you are engaged in information Olympiad, this function may not be compiled.
Please Baidu for specific usage.
3.sprint method
Recommendation: 2 stars ★★
This method can only convert int to char. However, it can also achieve the purpose in combination with atoi. It is a standard C function
code:
int num=1234567; sprintf(str, "%d", num); //At this point, str is "1234567". Note that str is a char array
4. Enumeration judgment method
Recommendation: 0 star
Well... It's if(a = '1') b=1
I've learned OI, so I'm not going to do it like this?
0.6 others (negative division and remainder)
1: As for division, both positive and negative numbers are rounded to 0: 10 / 4 = 2, 10 / (- 4) = - 2
2: Negative remainder is determined by modulus
|Small |% | big | = | small |, the symbol is the same as before |; large |% | small | = |, the symbol of remainder is the same as before
3%4 = 3 ; -3%4 = -3 ; -3%-4 = -3 ; 3%-4 = 3; 5%3 = 2 ; 5%-3 = 2 ;-5%-3 = -2 ; -5%3 = -2;
3: When converting a floating-point number to an int, the decimal part will be omitted. Note that it is not rounded~~
#include <iostream> using namespace std; int main(int argc,char** argv) { int a = 8.5; cout<<a<<endl;//Output 8 cin.get(); return 0; }
4: Strictly speaking, different compilers have different situations in the division of negative numbers; however, in the GCC compiler, the symbols of the remainder and the dividend are the same
(prevent white ~ "14 ➗ "2" is read as "Fourteen divided by two". The divisor is preceded by "divisor" and the divisor is followed by "divisor")
With this in mind, most cases of C/C + + can be solved. In the remainder operation, first take the absolute value for calculation, and then judge the symbol
1. Related topics
1.1 container with the most water
- Container with the most water
Give you n nonnegative integers a1, a2,..., an, each representing a point (i, ai) in the coordinate. Draw n vertical lines in the coordinate. The two endpoints of the vertical line i are (i, ai) and (i, 0). Find out the two lines so that the container composed of them and the x-axis can hold the most water.
Note: you cannot tilt the container.
Example 1:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: the vertical line in the figure represents the input array [1,8,6,2,5,4,8,3,7]. In this case, the maximum value that the container can hold water (represented by the blue part) is 49.
Example 2:
Input: height = [1,1]
Output: 1
Example 3:
Input: height = [4,3,2,1,4]
Output: 16
Example 4:
Input: height = [1,2,1]
Output: 2
My solution
int maxArea(vector<int>& height) { int res = 0; int l = 0, r = height.size()-1; while(l < r){ int nowHeight = height[l] < height[r] ? height[l++] : height[r--]; // Pay attention to + + / after here-- res = max(res, (r - l + 1)*nowHeight); } return res; }
Prove why - use the left and right pointers to narrow the range in turn.
prove
Why is the double pointer correct?
What does a double pointer represent?
Double pointers represent the range of all positions that can be used as container boundaries. At the beginning, the double pointer points to the left and right boundaries of the array, indicating that all positions in the array can be used as the boundaries of the container, because we haven't tried anything yet. After that, every time we move the pointer with the smaller number to another pointer, it means that we think this pointer can no longer be used as the boundary of the container.
Why can't the pointer with the smaller number be used as the boundary of the container?
In the above analysis, we have some preliminary ideas on this problem. Here we prove it quantitatively.
Consider the first step, assuming that the current number of left pointer and right pointer are x and Y respectively, without losing generality, we assume that x ≤ y. At the same time, the distance between the two pointers is t. Then, the capacity of the container composed of them is:
min(x,y)∗t=x∗t
We can conclude that if we keep the position of the left pointer unchanged, the capacity of this container will not exceed x * t no matter where the right pointer is. Note that the right pointer can only move to the left here, because we are considering the first step, that is, when the pointer still points to the left and right boundaries of the array.
If we arbitrarily move the right pointer to the left, the number pointed to is y1, and the distance between the two pointers is t1, then obviously t1 < T, and
Therefore:
min(x,yt)∗t1<min(x,y)∗t min(x,y )∗t <min(x,y)∗t
That is, no matter how we move the right pointer, the capacity of the container is less than that of the container before moving. In other words, the number corresponding to the left pointer will not be used as the boundary of the container, so we can discard this position and move the left pointer to the right by one position. At this time, the new left pointer may be used as the boundary of the container only at the left and right positions between the original right pointers.
In this way, we reduce the scale of the problem by 111, and the position we discard is equivalent to disappearing. At this time, the left and right pointers point to the left and right boundaries of a new and reduced problem array. Therefore, we can continue to consider this problem as in the first step before:
-
Calculate the capacity of the container corresponding to the current double pointer;
-
The pointer with the smaller number cannot be used as the boundary of the container in the future. Discard it and move the corresponding pointer.
What is the final answer?
The answer is the maximum value of the capacity calculated each time using the double pointer as the left and right boundaries (that is, the left and right boundaries of the "array").
1.2 removing duplicate letters
- Remove duplicate letters
Give you a string s, please remove the repeated letters in the string so that each letter appears only once. Ensure that the dictionary order of the returned results is the smallest (it is required not to disturb the relative positions of other characters).
Note: this question is similar to 1081 https://leetcode-cn.com/problems/smallest-subsequence-of-distinct-characters identical
Example 1:
Enter: s = "bcabc"
Output: "abc"
Example 2:
Input: s = "cbacdcbc"
Output: "acdb"
My solution
#include <algorithm> #include <cmath> #include <deque> #include <iostream> #include <list> #include <queue> #include <set> #include <sstream> #include <stack> #include <unordered_map> #include <map> #include <vector> using namespace std; #define For(x,y,z) for(ll x = y; x < z;++x) typedef long long ll; class Solution { public: /** * @Description: The container is not accessed every time the stack is used (because the letters should be unique); If the container is not empty and the element at the top of the stack is larger than the current element, it should be out of the stack. * @param {string} s * @return {*} * @notes: */ string removeDuplicateLetters(string s) { unordered_map<char, int> strMap; for(char ch : s){ strMap[ch] ++; // cout << "strmap[" << ch << "]:" << strMap[ch] << endl; } vector<int> visited(26, 0); stack<char> stackStr; for(char ch : s){ if(!visited[ch - 'a']){ // Always judge to remove large ones, and sometimes later while(!stackStr.empty() && stackStr.top() > ch){ // cout << stackStr.top() << endl; if(strMap[stackStr.top()] > 0){ // Others / / can't be used. count is used to calculate the number of keys. There are always keys; But use the number of num inside! visited[stackStr.top() - 'a'] = 0; // cout << "strmap[" << ch << "]:" << strMap[ch] << endl; // cout << "pop while:" << stackStr.top() << endl; stackStr.pop(); }else{ break; } } // Stack is empty or the current element is unique or not greater than the current stack top element // Are directly into the stack visited[ch - 'a'] = 1; stackStr.push(ch); // cout << "not visited push ch:" << ch << endl; } // Visited-- strMap[ch] --; } string res; while(!stackStr.empty()){ res.push_back(stackStr.top()); stackStr.pop(); } reverse(res.begin(), res.end()); return res; } }; int main(int argc, char const *argv[]) { Solution s; cout << s.removeDuplicateLetters("cbacdcbc") << endl; system("pause"); return 0; }
1.3 twenty six letters before and after cycle unlocking
My solution
string dec(string str, int up_char_offset, int low_char_offset){ string res; for( char ch : str ){ // Capitalize if(ch>='A' && ch <= 'Z'){ res.push_back( (char)( (ch - 'A' + up_char_offset + 26) % 26 + 65) ); }else if (ch >= 'a' && ch <= 'z') { res.push_back( (char)( (ch - 'a' + low_char_offset + 26) % 26 + 97) ); }else{ res.push_back(ch); } } cout << res << endl; return res; } int main(int argc, char const *argv[]) { cout << dec("Def Z", -1, 1) << endl; system("pause"); return 0; }