Problem:
Score : 300 points

Problem Statement

You are given a string S consisting of lowercase English letters.
Another string T is initially empty.
Determine whether it is possible to obtain S = T by performing the following operation an arbitrary number of times:

Append one of the following at the end of T: dream, dreamer, erase and eraser.

Constraints

1≦|S|≦10^5

S consists of lowercase English letters.

Input

The input is given from Standard Input in the following format:

S

Output

If it is possible to obtain S = T, print YES. Otherwise, print NO.

Sample Input 1

erasedream

Sample Output 1

YES

Append erase and dream at the end of T in this order, to obtain S = T.

Sample Input 2

dreameraser

Sample Output 2

YES

Append dream and eraser at the end of T in this order, to obtain S = T.

Sample Input 3

dreamerer

Sample Output 3

NO

Solution in JavaScript (node.js v5.12) (judge verdict: Wrong Answer)

'use strict'
const main = arg => {
	const input = arg.trim().split("\n");
	let s = input[0]
	const parts = ['dream', 'dreamer', 'erase', 'eraser']
	const replaced = []
	let failure = 0
	let sameCount = 0
	//replaceを続け、replaceできなくなったら一つ戻る
	while(1) {
		for(let i = 0 ; i < parts.length ; i++) {
			
			let before = s
			s = s.replace(new RegExp('^' + parts[i]), '')
			if(s === '') {
				console.log('YES')
				return
			}
			if(s === before) {
				sameCount++
			} else {
				sameCount = 0
				failure = 0
				replaced.push({moji: parts[i], idx: i})
			}
			if(sameCount >= parts.length - 1) {
				failure++
				// １つ前の選択肢を戻す
				s = replaced[replaced.length - 1].moji + s
				i = replaced[replaced.length - 1].idx
			}
			if(failure >= parts.length) {
				console.log('NO')
				return
			}
		}
	}
}   
main(require('fs').readFileSync('/dev/stdin', 'utf8'));