当前位置:网站首页>牛客 BM83 字符串变形(大小写转换,字符串反转,字符串替换)
牛客 BM83 字符串变形(大小写转换,字符串反转,字符串替换)
2022-07-03 14:37:00 【嘻嘻作者哈哈】
- 题目:BM83 字符串变形
思路
- 转换大小写。遍历字符串,遇到小写字母,转换成大写,遇到大写字母,转换成小写,遇到空格正常不变。
- 反转整个字符串。
- 以空格为界限,对每一个单词单独进行反转。
import java.util.*;
public class Solution {
public String trans(String s, int n) {
// write code here
int len = s.length();
StringBuilder res = new StringBuilder(len);
// 第一步:转换大小写
for(int i = 0; i < len; ++i){
char cur = s.charAt(i);
if(cur >= 'a' && cur <= 'z'){
res.append((char)(cur - 'a' + 'A')); // 小写变大写
} else if(cur >= 'A' && cur <= 'Z'){
res.append((char)(cur - 'A' + 'a')); // 大写变小写
} else{
res.append(cur); // 空格
}
}
// 第二步:翻转整个字符串
res = res.reverse();
// 第三步:单个单词进行翻转
int i = 0;
int j = 0;
while(i < len){
j = i; // 指向空格
// 以空格为边界,翻转一个单词
while(j < len && res.charAt(j) != ' '){
++j;
}
// 截取[i, j)区间的子串
StringBuilder word = new StringBuilder(res.substring(i, j));
word = word.reverse(); // 翻转单词
res.replace(i, j, word.toString()); // 替换原单词
i = j + 1; // 从下一个单词开始
}
return res.toString();
}
}
总结
- 小写变大写:
ch = ch - 'a' + 'A' - 大写变小写:
ch = ch - 'A' + 'a' - 字符串反转:
str = str.reverse() - 截取子串:
sub = str.substring(start, end) - 子串替换:
str.replace(start, end, str1)
边栏推荐
- 556. 下一个更大元素 III : 简单构造模拟题
- Luogu p4047 [jsoi2010] tribal division solution
- Zzuli:1058 solving inequalities
- Raft agreement
- Timecho of Tianmou technology completed an angel round financing of nearly 100 million yuan to create a native timing database of the industrial Internet of things
- Add ZABBIX calculation type itemcalculated items
- 编程语言:类型系统的本质
- Niuke: crossing the river
- Puzzle (016.3) is inextricably linked
- Zzuli:1052 sum of sequence 4
猜你喜欢

Use of form text box (I) select text

Mysql多表查询 #子查询

retrofit

ShowMeBug入驻腾讯会议,开启专业级技术面试时代

Analysis of gene family characteristics - chromosome location analysis

7-18 finding the single root of polynomial by dichotomy

Accelerating strategy learning using parallel differentiable simulation

Zhonggan micro sprint technology innovation board: annual revenue of 240million, net loss of 17.82 million, proposed to raise 600million

使用并行可微模拟加速策略学习

How to query the baby category of tmall on Taobao
随机推荐
洛谷P4047 [JSOI2010]部落划分 题解
7-20 print 99 formula table (format output)
tonybot 人形机器人 定距移动 代码编写玩法
【7.3】146. LRU缓存机制
Zzuli: cumulative sum of 1050 factorials
dllexport和dllimport
7-2 and then what time (15 minutes)
Zzuli: sum of 1051 square roots
556. The next larger element III
7-16 find the set of integers that meet the given conditions
Detailed explanation of four modes of distributed transaction (Seata)
Zzuli:1044 failure rate
Dllexport et dllimport
How Facebook moves instagram from AWS to its own server
Convert string to decimal integer
亚马逊、速卖通、Lazada、Shopee、eBay、wish、沃尔玛、阿里国际、美客多等跨境电商平台,测评自养号该如何利用产品上新期抓住流量?
光猫超级账号密码、宽带账号密码 获取
US stock listing of polar: how can the delivery of 55000 units support the valuation of more than 20billion US dollars
Programming language: the essence of type system
洛谷P5194 [USACO05DEC]Scales S 题解