Wednesday, October 10, 2018

[LeetCode]Reverse Only Letters


很简单的题,我们用两个指针,一头一尾,头指针指向字母的时候,append尾指针应该指向的字符;头指针指向非字母的时候,append当前字符即可。时间复杂度O(N),空间复杂度,如果不考虑返回结果所需要的空间的话是常数。代码如下:


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