当前位置:网站首页>牛客 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)
边栏推荐
- 7-3 rental (20 points)
- Zzuli:1045 numerical statistics
- 1017 a divided by B (20 points)
- J-luggage lock of ICPC Shenyang station in 2021 regional games (simple code)
- 7-14 sum integer segments (C language)
- Detailed explanation of four modes of distributed transaction (Seata)
- Tonybot humanoid robot infrared remote control play 0630
- 7-3 count the number of words in a line of text
- Niuke: crossing the river
- Paper sharing: generating playful palettes from images
猜你喜欢
Puzzle (016.3) is inextricably linked
retrofit
Sword finger offer 28 Symmetric binary tree
Analysis of gene family characteristics - chromosome location analysis
Tiantu investment sprint Hong Kong stocks: asset management scale of 24.9 billion, invested in xiaohongshu and Naixue
Accelerating strategy learning using parallel differentiable simulation
Showmebug entered Tencent conference, opening the era of professional technical interview
提高效率 Or 增加成本,开发人员应如何理解结对编程?
puzzle(016.4)多米诺效应
tonybot 人形机器人 查看端口并对应端口 0701
随机推荐
2021-10-16 initial programming
retrofit
【北大青鸟昌平校区】互联网行业中,哪些岗位越老越吃香?
7-6 mixed type data format input
Common shortcut keys in PCB
Thread. Sleep and timeunit SECONDS. The difference between sleep
Sendmail无法发送邮件及发送过慢解决
Facebook 如何将 Instagram 从 AWS 搬到自己的服务器
Add ZABBIX calculation type itemcalculated items
光猫超级账号密码、宽带账号密码 获取
Use of form text box (I) select text
亚马逊、速卖通、Lazada、Shopee、eBay、wish、沃尔玛、阿里国际、美客多等跨境电商平台,测评自养号该如何利用产品上新期抓住流量?
Zzuli:1055 rabbit reproduction
Ultra simple mobile map development
7-3 count the number of words in a line of text
Optical cat super account password and broadband account password acquisition
7-10 stack of hats (25 points) (C language solution)
Four data flows and cases of grpc
关于敏捷的一些概念
7-2 and then what time (15 minutes)