• [LeetCode]344.Reverse String


    题目描述:

    Write a function that takes a string as input and returns the string reversed.

    思路:

    逆序输出一个字符串
    第一种方法:
    从尾到头遍历原字符串,返回到result中。但提交提示超时了,给了一个巨长无比的测试用例。
    第二种方法,从0-s.length()/2,依次交换头和尾的字符 时间复杂度减半
    注意。将string转为char 用charAt()将String中某一位转为char.或者s.toCharArray()可以将整个string转为char
    char转string则使用new String(ch)方法
    第三种方法,使用栈。后进先出
    将s入栈,然后出栈存入result
    但还是 Time Limit Exceeded

    public class Solution344 {
        public String reverseString(String s) {
            //方法1,遍历。超时
            /*String result = "";
            for(int i = s.length()-1; i >=0;i--){
                result += s.charAt(i);
            }
            return result;*/
            //方法2,从0-s.length()/2,依次交换头和尾的字符   时间复杂度减半
            /*int i=0,j=s.length()-1;
            char ch[] = s.toCharArray();
            char temp;
            while(i<s.length()/2){
                temp = s.charAt(i);
                ch[i]    = ch[j];    
                ch[j] = temp;
                i++;
                j--;
            }
            return new String(ch);*/
            Stack<Character> stack = new Stack<>();
            int i = 0;
            String result = "";
            while(i < s.length()){
                stack.push(s.charAt(i));
                i++;
            }
            while(!stack.isEmpty()){
                result+=stack.pop();
            }
            return result;
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Solution344 solution344 = new Solution344();
            String s = "hello";
            System.out.println(solution344.reverseString(s));
        }
    
    }
  • 相关阅读:
    php编程规范整理
    约瑟夫环问题的实现
    MYSQL中SHOW的使用整理收藏
    mysql使用存储过程&函数实现批量插入
    浅谈select for update 和select lock in share mode的区别
    jQuery对象扩展方法(Extend)深度解析
    WCF系列教程之WCF操作协定
    WCF系列教程之WCF实例化
    WCF系列教程之WCF中的会话
    WCF系列教程之WCF服务协定
  • 原文地址:https://www.cnblogs.com/zlz099/p/8250540.html
Copyright © 2020-2023  润新知