HR30 Day 18: Queues and Stacks/PHP

Jmnote (토론 | 기여)님의 2018년 8월 15일 (수) 16:55 판 (→‎개요)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

개요[ | ]

상단
<?php
구현예시 1
class Solution {
    // Write your code here
    private $stack = [];
    private $queue = [];
    function pushCharacter($ch) {
        array_push($this->stack, $ch);
    }
    function enqueueCharacter($ch) {
        array_push($this->queue, $ch);
    }
    function popCharacter() {
        return array_pop($this->stack);
    }
    function dequeueCharacter() {
        return array_shift($this->queue);
    }
}
구현예시 2
class Solution {
    // Write your code here
    private $stack;
    private $queue;
    function __construct() {
        $this->stack = new SplStack();
        $this->queue = new SplQueue(); 
    }
    function pushCharacter($ch) {
        $this->stack->push($ch);
    }
    function enqueueCharacter($ch) {
        $this->queue->enqueue($ch);
    }
    function popCharacter() {
        return $this->stack->pop();
    }
    function dequeueCharacter() {
        return $this->queue->dequeue();
    }
}
하단
// read the string s
$s = fgets(STDIN);
// create the Solution class object p
$obj = new Solution();
$len = strlen($s);
$isPalindrome = true;

// push/enqueue all the characters of string s to stack
for ($i = 0; $i < $len; $i++) {
    $obj->pushCharacter($s{$i});
    $obj->enqueueCharacter($s{$i});
}
/*
pop the top character from stack
dequeue the first character from queue
compare both the characters
*/
for ($i = 0; $i < $len / 2; $i++) {
    if($obj->popCharacter() != $obj->dequeueCharacter()){
        $isPalindrome = false;
        break;
    }
}

//finally print whether string s is palindrome or not.
if ($isPalindrome)
    echo "The word, ".$s.", is a palindrome.";
else
    echo "The word, ".$s.", is not a palindrome.";
?>
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}