当前位置:网站首页>牛客 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)
边栏推荐
猜你喜欢

pyQt界面制作(登录+跳转页面)

X86 assembly language - Notes from real mode to protected mode

Tonybot humanoid robot starts for the first time 0630

How to query the baby category of tmall on Taobao

Detailed explanation of four modes of distributed transaction (Seata)

Mysql多表查询 #子查询

puzzle(016.3)千丝万缕

Happy capital new dual currency fund nearly 4billion yuan completed its first account closing

表单文本框的使用(一) 选择文本

retrofit
随机推荐
Sub GHz wireless solution Z-Wave 800 Series zg23 SOC and zgm230s modules
Find books ()
LNMP环境mail函数不能发送邮件解决
Dllexport and dllimport
基因家族特征分析 - 染色体定位分析
String sort
7-10 stack of hats (25 points) (C language solution)
puzzle(016.3)千丝万缕
洛谷P5018 [NOIP2018 普及组] 对称二叉树 题解
Time conversion ()
How Facebook moves instagram from AWS to its own server
洛谷P5536 【XR-3】核心城市 题解
How to query the baby category of tmall on Taobao
Adc128s022 ADC Verilog design and Implementation
洛谷P4047 [JSOI2010]部落划分 题解
Frequently asked questions: PHP LDAP_ add(): Add: Undefined attribute type in
Tonybot humanoid robot starts for the first time 0630
Paper sharing: generating playful palettes from images
使用并行可微模拟加速策略学习
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon