• 《Java数据结构与算法》笔记CH42用栈实现字符串反转


    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    //用栈来实现一个字符串逆序算法
    /**
     * 数据结构:栈
     */
    class StackW{
    	private int maxSize;
    	private char[] stackArray;
    	private int top;
    	public StackW(int max){
    		maxSize = max;
    		stackArray = new char[maxSize];
    		top = -1;
    	}
    	public void push(char c){
    		stackArray[++top] = c;
    	}
    	public char pop(){
    		return stackArray[top--];
    	}
    	public char peek(){
    		return stackArray[top];
    	}
    	public boolean isEmpty(){
    		return (top == -1);
    	}
    	public boolean isFull(){
    		return (top == maxSize);
    	}
    }
    /**
     * 反转类
     */
    class Reverser{
    	private String input;
    	private StringBuilder output;
    	public Reverser(String in){
    		input = in;
    		output = new StringBuilder();
    	}
    	/**
    	 * 使用定义的栈来进行字符串的反转
    	 * @return
    	 */
    	public String doReverse(){
    		int stackSize = input.length();
    		StackW s = new StackW(stackSize);
    		for(int j= 0;j<stackSize;j++){
    			char c = input.charAt(j);
    			s.push(c);
    		}
    		while(!s.isEmpty()){
    			char ch = s.pop();
    			output.append(ch);
    		}
    		return output.toString();
    	}
    }
    public class WordReverse {
    	public static void main(String[] args) throws Exception {
    		String input, output;
    		while(true){
    			System.out.println("Enter a string");
    			System.out.flush();
    			input = getString();
    			if(input.equals(""))
    				break;
    			Reverser re = new Reverser(input);
    			output = re.doReverse();
    			System.out.println("reversed:"+output);
    		}
    	}
    	/**
    	 * 从键盘读字符串
    	 * @return
    	 * @throws Exception
    	 */
    	public static String getString() throws Exception{
    		InputStreamReader isr = new InputStreamReader(System.in);
    		BufferedReader br = new BufferedReader(isr);
    		String s = br.readLine();
    		return s;
    	}
    }
    

  • 相关阅读:
    小程序教程3
    小程序教程2
    小程序教程1
    sublime介绍常用插件和快捷键
    ionic1跨域问题
    上传文件到windows server, 导出文件到linux, 打包压缩
    windows远程管理服务winrm
    windows配置ssh服务
    前端:websocket脚本
    前端实现: 抓拍和定时弹出任务
  • 原文地址:https://www.cnblogs.com/fstack/p/5617262.html
Copyright © 2020-2023  润新知