题解 | #字符串变形#
字符串变形
https://www.nowcoder.com/practice/c3120c1c1bc44ad986259c0cf0f0b80e
class Solution { public: //用于字母大小写转换 void change(string& s, int n) { for (int i = 0; i < n; i++) { if (s[i] >= 'a' && s[i] <= 'z') { s[i] -= 32; } else if (s[i] >= 'A' && s[i] <= 'Z') { s[i] += 32; } else { continue; } } } //用于反转字符串 void reserve(string& s, int left,int right) { char ch; while (left < right) { ch = s[left]; s[left] = s[right]; s[right] = ch; left++; right--; } } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @param n int整型 * @return string字符串 */ string trans(string s, int n) { if (s == "" || n <= 0) return ""; //1、转换字母大小写 change(s, n); //2、反转整个字符串 reserve(s,0, n-1); //3、反转每个单词,当快指针走到'\0'处结束 int slow = 0; int fast = 0; while (1) { if (s[fast] == ' '||s[fast]=='\0') { reserve(s, slow, fast-1); if (fast == n) break; fast++; slow = fast; } else { fast++; } } return s; } //比如:Hello World //第一步处理大小写:hELLO wORLD //第二步反转整个字符串:DLROw OLLEh //第三步反转每个单词:wORLD hELLO };