题解 | #推箱子#
推箱子
http://www.nowcoder.com/practice/2b11fcf1926744889a71e72d1fbf7f89
值得注意的两点 1、字符串全是英文 没有中文 直接普通遍历即可 2、设置 x轴、y轴两个变量 解决
//import "fmt"
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param forwards string字符串 推箱子方向
* @return bool布尔型
*/
//注意:若字符串中包含中文
//那么传统的遍历字符串的方式就是错误,因为传统的对字符串的遍历是按照字节来遍历
//在utf-8中,一个汉字是3字节,一个字母是1个字节。
//解决方法是将str转为[]rune切片:
func pushBox(forwards string) bool {
// write code here
var x int
var y int
length := len(forwards)
for i := 0; i < length; i++ {
cur := forwards[i]
switch cur {
case 'U':y++
case 'D':y--
case 'L':x--
case 'R':x++
}
}
return x == 0 && y == 0
}