当前位置:网站首页>LeetCode · Question of the Day · 1417. Reformatting String · Simulation

LeetCode · Question of the Day · 1417. Reformatting String · Simulation

2022-08-11 10:33:00 Xiao Xun wants to become stronger

Link: https://leetcode.cn/problems/reformat-the-string/solution/by-xun-ge-v-aazm/
Source: LeetCode
Copyright belongs to the author.For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Title

Example

Thoughts

Solution ideas
According to the meaning of the question, we need to reconstruct a string, which must be followed by letters and numbers, and numbers should be followed by letters.
So only when the difference between the number of characters and the number of digits in the string is less than 1, it can be constructed

I can't think of it through simple analog construction. When there are more characters or numbers, we must start from the one with more characters. Because there is one more, we must start and put one at the end to meet the requirements

It is more convenient to use double pointers during construction

Code comments are super detailed

Code

char * reformat(char * s){int len ​​= strlen(s);// Find the length of the stringint sum = 0;for(int i = 0; i < len; i++)//traverse the string to find the length of the number{char ch = s[i];if (isdigit(ch)) {//Determine whether the character is a digital functionsum++;}}int summ = len - sum;if(abs(summ - sum) > 1)//Judge the difference{return "";}int logo = summ > sum ? 1 : 0;for(int i = 0, j = 0; i < len; i++){if(logo == 1)//There are many letters, the letters are constructed first{if(!isdigit(s[j]) && j == 0)//The beginning is a letter, no additional processing is required{j++;continue;}}else//There are many numbers, the numbers are constructed first{if(isdigit(s[j]) && j == 0)//The beginning is a number, no additional processing is required{j++;continue;}}//If the beginning does not meet the requirements, it is actually the same as the usual construction process.//When the elements pointed to by the two pointers are the same, the slow pointer stays at the current position, and the fast pointer finds a different element and exchanges it with itif( (isdigit(s[j]) && isdigit(s[i])) || (!isdigit(s[j]) && !isdigit(s[i])) ){continue;}char ch = s[i];s[i] = s[j];s[j] = ch;j += 2;}return s;}Author: xun-ge-vLink: https://leetcode.cn/problems/reformat-the-string/solution/by-xun-ge-v-aazm/Source: LeetCodeCopyright belongs to the author.For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

原网站

版权声明
本文为[Xiao Xun wants to become stronger]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/223/202208111025349579.html