forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
46 lines (36 loc) · 935 Bytes
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/// Source : https://leetcode.com/problems/reverse-only-letters/description/
/// Author : liuyubobobo
/// Time : 2018-10-06
#include <iostream>
using namespace std;
/// Two Pointers
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
string reverseOnlyLetters(string S) {
int i = nextLetter(S, 0), j = prevLetter(S, S.size() - 1);
while(i < j){
swap(S[i], S[j]);
i = nextLetter(S, i + 1);
j = prevLetter(S, j - 1);
}
return S;
}
private:
int nextLetter(const string& s, int start){
for(int i = start; i < s.size(); i ++)
if(isalpha(s[i]))
return i;
return s.size();
}
int prevLetter(const string& s, int start){
for(int i = start; i >= 0; i --)
if(isalpha(s[i]))
return i;
return -1;
}
};
int main() {
return 0;
}