很简单的题,我们用两个指针,一头一尾,头指针指向字母的时候,append尾指针应该指向的字符;头指针指向非字母的时候,append当前字符即可。时间复杂度O(N),空间复杂度,如果不考虑返回结果所需要的空间的话是常数。代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
string reverseOnlyLetters(string S) { | |
int len = S.size(); | |
string res; | |
int i = 0, j = len - 1; | |
while (i < len) | |
{ | |
char c = S[i]; | |
if (isalpha(c)) | |
{ | |
while (j >= 0 && !isalpha(S[j]))--j; | |
res += S[j--]; | |
} | |
else | |
res += S[i]; | |
++i; | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment