917. Reverse Only Letters
Given a string S
, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"
Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
Note:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S
doesn't contain\
or"
只翻转英文字母。
#include<vector> #include <cstdlib> #include<iostream> #include <unordered_set> #include <algorithm> #include<string> using namespace std; class Solution { public: string reverseOnlyLetters(string S) { int n = S.size(); int i = 0, j = n - 1; while (i < j) { while (!isalpha(S[i]) && i < j) i++; while (!isalpha(S[j]) && j > i) j--; //std::cout << "S[i] " << S[i] << " S[j] " << S[j] << endl; // char tmp = S[i]; // S[i] = S[j]; // S[j] = tmp; swap(S[i], S[j]); i++, j--; } return S; } }; int main() { string S = "Test1ng-Leet=code-Q!"; Solution solution; std::cout << solution.reverseOnlyLetters(S) << std::endl; return 0; }
Your runtime beats 100.00 % of cpp submissions
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步