【20210414华为机试】第一题:字符数翻转 Python和C++实现

题目描述

给出一个字符串s(仅含有小写英文字母和括号)。请你按照从内层到外层的顺序,逐层反转每对匹配括号内包含的字符串,并返回最终的结果。

输入描述:

输入为一行带有括号的字符串(只包含英文小写字母和左右小括号,且
左右括号是成对的)
最大长度不会超过1000个字符。

输出描述:

反转括号内字符串并输出(只有英文小写字母)

示例 1
输入
(u(love)i)

输出
iloveu
示例 2
输入
((jhku)(love)i)

输出
ilovejhku
代码思路

在这里插入图片描述

Python 代码
class Solution_hw(object):
    def __init__(self):
        super(Solution_hw, self).__init__()
        self.input_str = ""
        self.stack_l = []

    def input_data(self, deBug=False):
        if deBug:
            self.input_str = "(u(love)i)"

        else:

            try:
                self.input_str = input("please input str : ")
            except:
                pass

    def reverse_str(self):
        # [1] reverse
        input_str_list = list(self.input_str) # "abc" -> ['a', 'b', 'c']

        for idx in range(len(input_str_list)):
            # save '(' idx
            if input_str_list[idx] == '(':
                self.stack_l.append(idx)

            # pop '(' idx
            if input_str_list[idx] == ')':
                l_idx = self.stack_l[-1]
                self.stack_l.pop()

                # reverse [l_idx,idx]
                input_str_list[l_idx+1:idx] = input_str_list[l_idx+1:idx][::-1]

        # [2] pop '(' & ')'
        out_str = ""
        for c in input_str_list:
            if c == '(' or c == ')':
                continue
            out_str += c

        return out_str

    def output_info(self):
        print(self.reverse_str())




if __name__ == '__main__':
    so = Solution_hw()
    so.input_data(deBug=False)
    so.output_info()

C++ 代码
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

class Solution_hw_01
{
public:
    Solution_hw_01() {}
    string reverse_my(string s)
    {
        string str(s);
        int len = str.size();
        stack<int> s_k;
        for(int i = 0; i < len; i++)
        {
            char char_c = str.at(i);

            if(char_c =='(')
            {
                s_k.push(i);
            }
            else if (char_c == ')')
            {
                int iter = s_k.top();
                s_k.pop();
                // 翻转[start_idx, end_dix)
                reverse(str.begin()+iter+1, str.begin()+i);

            }
        }
        auto iter = str.begin();
        auto end = str.end();

        while (iter != end)
        {
            if(*iter == '(' || *iter == ')')
            {
                iter = str.erase(iter);
            }
            else
            {
                iter++;
            }
        }
        return str;
    }
};


int main(int argc, char *argv[])
{
    string input;
    cin >> input;

//    string input = "(u(love)i)";          // (u(love)i) -> (uevoli) -> iloveu
//    string input = "((jhku)(love)i)";     // ((jhku)(love)i) -> (ukhjevoli) -> ilovejhku
    Solution_hw_01 so;
    string ret = so.reverse_my(input);
    cout << ret << endl;

    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值