> Java > java지도 시간 > 본문

Java 예 - 문자열 반전을 달성하기 위한 푸시 및 팝 메소드

黄舟
풀어 주다: 2017-02-04 09:59:32
원래의
1516명이 탐색했습니다.

다음 예에서는 문자열 반전을 달성하기 위해 사용자 정의 메서드 StringReverserThroughStack()을 사용하는 방법을 보여줍니다.

/*
 author by w3cschool.cc
 StringReverserThroughStack.java
 */import java.io.IOException;public class StringReverserThroughStack {
   private String input; 
   private String output;
   public StringReverserThroughStack(String in) {
      input = in;
   }
   public String doRev() {
      int stackSize = input.length(); 
      Stack theStack = new Stack(stackSize); 
      for (int i = 0; i < input.length(); i++) {
         char ch = input.charAt(i); 
         theStack.push(ch); 
      }
      output = "";
      while (!theStack.isEmpty()) {
         char ch = theStack.pop(); 
         output = output + ch; 
      }
      return output;
   }
   public static void main(String[] args) 
   throws IOException {
      String input = "www.w3cschool.cc";
      String output;
      StringReverserThroughStack theReverser = 
      new StringReverserThroughStack(input);
      output = theReverser.doRev();
      System.out.println("反转前: " + input);
      System.out.println("反转后: " + output);
   }
   class Stack {
      private int maxSize;
      private char[] stackArray;
      private int top;
      public Stack(int max) {
         maxSize = max;
         stackArray = new char[maxSize];
         top = -1;
      }
      public void push(char j) {
         stackArray[++top] = j;
      }
      public char pop() {
         return stackArray[top--];
      }
      public char peek() {
         return stackArray[top];
      }
      public boolean isEmpty() {
         return (top == -1);
      }
   }}
로그인 후 복사

위 코드를 실행한 결과는 다음과 같습니다.

反转前:  
反转后: cc.loohcsc3w.www
로그인 후 복사

위는 Java 예제 - 문자열 반전을 달성하기 위해 스택을 푸시하고 팝하는 방법에 대한 자세한 내용은 PHP 중국어 웹사이트(www.php.cn)를 참고하세요!


원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!