当前位置:网站首页>LeetCode·每日一题·1417.重新格式化字符串·模拟
LeetCode·每日一题·1417.重新格式化字符串·模拟
2022-08-11 10:26:00 【小迅想变强】
链接:https://leetcode.cn/problems/reformat-the-string/solution/by-xun-ge-v-aazm/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
题目
示例
思路
解题思路
根据题意,我们需要重新构造一个字符串,该字符串必须字母后面应该跟着数字,而数字后面应该跟着字母。
所以只有当字符串中 字符个数 和 数字个数 相差小于 1 时,才能构造
通过简单模拟构造不能想到,当字符或者数字任意一个较多时,我们必须从多的那个开始构造字符串,因为多一个所以必须开始放一个结束放一下才满足要求
构造过程使用双指针更加方便
代码注释超级详细
代码
char * reformat(char * s){
int len = strlen(s);//求字符串长度
int sum = 0;
for(int i = 0; i < len; i++)//遍历字符串求数字长度
{
char ch = s[i];
if (isdigit(ch)) {//判断字符是否为数字函数
sum++;
}
}
int summ = len - sum;
if(abs(summ - sum) > 1)//判断差值
{
return "";
}
int logo = summ > sum ? 1 : 0;
for(int i = 0, j = 0; i < len; i++)
{
if(logo == 1)//字母多,字母先构造
{
if(!isdigit(s[j]) && j == 0)//开头就是字母,不需要额外处理
{
j++;
continue;
}
}
else//数字多,数字先构造
{
if(isdigit(s[j]) && j == 0)//开头就是数字,不需要额外处理
{
j++;
continue;
}
}
//如果开头不满足要求,其实就和平常构造过程一样。
//当双指针指向的元素相同时,慢指针留在当前位置,快指针去找不同元素与其交换
if( (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;
}
作者:xun-ge-v
链接:https://leetcode.cn/problems/reformat-the-string/solution/by-xun-ge-v-aazm/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
边栏推荐
- 大家有遇到这种错吗?flink-sql 写入 clickhouse
- 7 天找个 Go 工作,Gopher 要学的条件语句,循环语句 ,第3篇
- Network model (U - net, U - net++, U - net++ +)
- MySQL表sql语句增删查改_查询
- Huawei WLAN Technology: AC/AP Experiment
- Simple implementation of a high-performance clone of Redis using .NET (seven-end)
- Simple strokes on the Internet
- 国产数据库有没有在国外的应用案例?
- servlet——servlet介绍 | 发布动态资源
- Convolutional Neural Network Gradient Vanishing, The Concept of Gradient in Neural Networks
猜你喜欢
计算数组某个元素的和
Primavera Unifier 自定义报表制作及打印分享
Simple implementation of a high-performance clone of Redis using .NET (seven-end)
php将form表单内容提交到数据库后中文变成??(问号)
HDRP shader gets pixel depth value and normal information
SAP 产品增强技术回顾
神经痛分类图片大全,神经病理性疼痛分类
SAP Product Enhancement Technology Review
华为WLAN技术:AC/AP 实验
使用stream实现两个list集合的合并(对象属性的合并)
随机推荐
LeetCode每日一题(1754. Largest Merge Of Two Strings)
【Prometheus】Alertmanager告警全方位讲解
B端产品需求分析与优先级判断
【分享】PPT还能做成这样?你一定没见过
Simple interaction between server and client
大疆2022秋招笔试 —— 最小时间差、数组的最小偏移量
Algorithm---Jumping Game (Kotlin)
How to improve the efficiency of telecommuting during the current epidemic, sharing telecommuting tools
idea plugin autofill setter
Deploying Robot Vision Models Using Raspberry Pi and OAK Camera
27岁了,目前从事软件测试,听些老一辈的人说测试前途是IT里最差的,是这样吗?
Network model (U - net, U - net++, U - net++ +)
力扣打卡----打家劫舍
Primavera Unifier 自定义报表制作及打印分享
突破次元壁垒,让身边的玩偶手办在屏幕上动起来!
【翻译】Drafting and Revision: Laplacian Pyramid Network for Fast High-Quality Artistic Style Transfer
人是怎么废掉的?人是怎么变强的?
假设检验:正态性检验的那些bug——为什么对同一数据,normaltest和ktest会得到完全相反的结果?
保证金监控中心保证期货开户和交易记录
Database Basics