第163题 JS反转字符串

实现字符串A1B2C3反转为3C2B1A

    // 方式1:str.split('').reverse().join('')
    
    // 方式2:使用栈来实现
    function reverseStr(str) {
      const stack = []
      for(let c of str) {
        stack.push(c) // 入栈
      }
      let newStr = ''
      let c = ''
      while(c = stack.pop()) { // 出栈 
        newStr += c // 出栈再拼接
      }
      return newStr
    }
    
    // 测试
    console.log(reverseStr('A1B2C3')) // 3C2B1A
Last Updated:
Contributors: leeguooooo