题解 | #字符串变形#
字符串变形
https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e
#include <algorithm>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param s string字符串
* @param n int整型
* @return string字符串
*/
void convert(char& c) {
if (c >= 'A' && c <= 'Z') {
c += 32;
} else {
c -= 32;
}
}
string trans(string s, int n) {
// write code here
reverse(s.begin(), s.end()); //整体反转
for (int i = 0; i < n; i++) {
// 改变大小写
if (s[i] != ' ') {
convert(s[i]);
}
}
for (int i = 0; i < n; i++) { //如何确定子串,并反转子串
int j = i;
while (s[j]!= ' ' && j < n) {
j++;
}
reverse(s.begin()+i, s.begin()+j);
i=j;
}
return s;
}
};
要求子串正常顺序,整体是反转的,那就是两次反转,整体先反转一次,此时子串也是反转的,再把每个子串反转回来。另外就是大小写转换。任务可以独立进行。大小写转换根据判断大小写,利用ASCII值直接转换。反转用内置函数reverse.难点在于确定反转子串的边界。子串是通过" "空格来分割的。那么
while (s[j]!= ' ' && j < n) {
j++;
}
这就是用来找子串的结束位置的,将子串的开始位置和结束位置传入reverse。第一个子串完成反转。那么考虑到可能不止一个子串。后续子串的位置如何确定呢,首先,第二个子串的开始位置可以根据第一个子串的结束位置确定。第二个子串的结束位置需要重新利用这样的循环来找对应的j。
文远知行公司福利 510人发布