z-sorts a given string from top to bottom, left to right, based on the number of rows given. For example, if the input string is “LEETCODEISHIRING” and the number of lines is 3, list it like this:
L C I R
E T O E S I I G
E D H N
After
, your output needs to be read line by line from left to right to produce a new string, such as “LCIRETOESIIGEDHN”.
:
string convert(string s, int numRows);
-
example 1:
input: s = “LEETCODEISHIRING”, numRows = 3
output: “LCIRETOESIIGEDHN” -
example 2:
input: s = “LEETCODEISHIRING”, numRows = 4
0 output: “LDREOEIIECIHNTSG”
interpretation :
LDR
EOEII
ECIHN
TSG
Source:
button force (LeetCode)
link: https://leetcode-cn.com/problems/zigzag-conversion p>
train of thought (have a reference problem solution)
- the first idea is to establish a two-dimensional array, violence will character in order fill in the li>
- set a says going in the direction of variables, when the z glyph to the first line/change direction when the last line li>
- dir represents a string array of rows, according to which line going to judge the next character is inserted into the li>
- finally connect string array all, become a string li> ul>
code h3>
class Solution { public: string convert(string s, int numRows) { if(numRows==1) { return s; } int n=s.length(); vector<string> rows(min(n,numRows)); int dir=0; bool going=false; for(char c : s) { rows[dir]+=c; if(dir==0 || dir==numRows-1) going=!going; dir+=going?1:-1; } string a; for(string x:rows) { a+=x; } return a; } };
summary h3>
- get a new method of traversing strings, but also understand the string connection
Read More:
- Transformation of JS map and JSON
- Dataframe and np.array The mutual transformation of
- In pandas, dataframe and np.array The mutual transformation between the two
- In Java, int is converted to string, and zero is added before the number of bits is insufficient
- Format control of cout cout.width () and cout.fill ()
- CIN in C + + cin.get ()、 cin.getline (), getline(), gets() function
- How to wrap a long string in MATLAB
- [Warning] incompatible implicit declaration of built-in function ‘strcat’
- Conversion from hexadecimal to decimal
- C++ —Return multiple values of different types
- C++: terminate called after throwing an instance of ‘std::length_error‘ (sort function cmp sorting rules problem)
- How to Fix TypeError: Cannot cast array data from dtype(‘float64‘) to dtype(‘<U32‘)….
- 1067 – Invalid default value for ‘sex‘1366 – Incorrect string value: ‘\xE6\x8A\x80\xE6\x9C\xAF…‘ f
- C++ cin.ignore Use of ()
- Java compareto() method
- Map to vector pair map.second sort
- Some problems in using arrays
- C++ string substr()
- Java.lang.Character . isdigit() and isletter() methods
- Solution of MySQL data garbled problem