LeetCode题解之 Reverse Only Letters

1、题目描述

2、题目描述

利用栈实现逆序。

 

3、代码

 1 string reverseOnlyLetters(string S) {
 2         if (S.size() == 0 || S.size() == 1)
 3             return S;
 4         
 5         stack<string> st;
 6         for (string::iterator it = S.begin(); it != S.end(); it++) {
 7             if ( isalpha(*it) ){
 8                 string sub = S.substr(it-S.begin(), 1);
 9                 st.push(sub);
10             }
11         }
12         
13         string res;
14         
15         for (auto it = S.begin(); it != S.end(); it++) {
16             if (isalpha(*it)) {
17                 string sub = st.top();
18                 st.pop();
19                 res += sub;
20             } else {
21                 string sub = S.substr(it - S.begin(),1);
22                 res += sub;
23             }
24         }
25         
26         return res;
27     }

 

posted @ 2019-02-22 12:41  山里的小勇子  阅读(124)  评论(0编辑  收藏  举报