原题是:
Given a string that contains exactly a single pair of parenthesis, return parenthesis and their contents, so "xyz(abc)123" yields "(abc)". etc.
Conditions:
1)No variable allowed
2)Collections not allowed
3)Regex, String.indexOf() not allowed.
大意就是不用任何变量、正则式来求出给定字符串有()的字符串子集。
如果可以使用局部变量的话,这道题是O(N)的解法,只要记住(的位置即可,但是现在不能。
一个解法是 如果字符串第一个不是(就++,最后一个不是)就--;string有这个sbustr可用,用递归来做就可以了。
#include <iostream>
#include <string>
using namespace std;
string findparenthesis(string s){
if (s.empty()){
return "";
}
if (s[0] == '('){
if (s[s.size()-1] == ')'){
return s;
}
else{
return findparenthesis(s.substr(0, s.length()-1));
}
}
else{
return findparenthesis(s.substr(1, s.length()-1));
}
}
int main(){
printf("%s", findparenthesis("xyz(abc)123").c_str());
}