2013-11-02 2 views
0

특정 작업이 있습니다. 우리는 "(() [] <>) 또는 이와 유사한 것에 대한 문자열을 가지고 있습니다. 인터뷰 질문 중 하나는 String이 맞는지 틀리는지를 확인하는 방법이었습니다. 예 : "() [] <" "- true,"([) "- false,"(()) "- false,"([<>]) "- 참입니다. 너희들 대단히 고마워! 내 코드에 문제가있을 수 없습니다. 많은 분들께 감사드립니다 !!! 도와주세요!스택을 사용하여 문자열을 확인하는 방법

import java.util.Stack;

공용 클래스 테스트 {

public static void main(String[] args) { 

    String line = "(<>()[])"; 
    Test test = new Test(); 
    boolean res = test.stringChecker(line); 
    System.out.println(res); 
} 

public boolean stringChecker(String line){ 
    boolean result = false; 
    char letter = '\u0000'; 
    char[] arr = line.toCharArray(); 
    Stack<Character> stack = new Stack(); 

    for (int i = 0; i < arr.length; i++) { 
     if (arr[i] == '(' || arr[i] == '[' || arr[i] == '<') { 
      stack.push(arr[i]); 
     } 
     if(arr[i] == ')' || arr[i] == ']' || arr[i] == '>'){ 
       if(stack.peek() == arr[i]){ 
        result = true; 
        stack.pop(); 

      } 
     } 
    } 

    return result; 
} 

}

+0

대단히 감사합니다! – Sergey

답변

2

(0) (그리고 당신은 <을 추진하고있다 {하지만 들여다 당신이>를 확인하고 있습니다), 그리고}

(1) 첫 번째 성공적인 일치에서 결과 false로 시작하여 true로 설정합니다. 대신 result true로 시작하여 실패한 첫 번째 일치 항목을 false로 설정해야합니다.

(2) 문자가 부족할 때 스택이 비어 있는지 확인해야합니다.

(3) 들여다보기 전에 스택이 비어 있는지 확인해야합니다.

(4) 예상하지 못한 문자가 있는지 확인하십시오. @TheodoreNorvell의 설명에 추가

+0

불행히도 편집 해 주셔서 감사합니다. AFK이므로 승인하지 못했습니다. 나는 전체 코드를 보여주기 위해 나의 대답을 편집했고, 그것을 다시 향상 시키도록 자유롭게 느낀다! – A4L

0

여기에 구현이 이러한 상황에 switch-caseif-else if-else보다 더 우아한 것을

public boolean stringChecker(String input) { 
    boolean result = true; 
    char[] arr = input.toCharArray(); 
    Stack<Character> stack = new Stack<>(); 
    try { 
     for (int i = 0; result && i < arr.length; i++) { 
      if (arr[i] == '(' || arr[i] == '[' || arr[i] == '<') { 
       stack.push(arr[i]); 
      } else if(arr[i] == ')') { 
       Character c = stack.pop(); 
       result = c.equals('('); 
      } else if(arr[i] == ']') { 
       Character c = stack.pop(); 
       result = c.equals('['); 
      } else if(arr[i] == '>') { 
       Character c = stack.pop(); 
       result = c.equals('<'); 
      } else { 
       // found some char that is not allowed 
       // here it is not just ignored, 
       // it invalidates the input 
       result = false; 
      } 
     } 
     // when the teher is not more chars in the array 
     // the stack has to be empty 
     result = result && stack.isEmpty() ; 
    } catch(EmptyStackException e) { 
     // found a closing bracket in the array 
     // but there is nothing on the stack 
     result = false; 
    } 
    return result; 
} 

@Test 
public void stringChecker() { 
    Assert.assertTrue(stringChecker("[]")); 
    Assert.assertTrue(stringChecker("[(<>)]")); 
    Assert.assertFalse(stringChecker("([<>)]")); 
    Assert.assertFalse(stringChecker(">")); 
    // invalid char 
    Assert.assertFalse(stringChecker("<[]e>")); 
    // stack is not empty 
    Assert.assertFalse(stringChecker("(")); 
} 

주처럼 보일 수있는 방법입니다.

관련 문제