Question:
让设计一个机器人,实现前进,向右转以及输出当前位置的功能(面经题,之前是乌龟来着),一开始在原点坐标,不能去负的坐标,去的话报错。
follow1:输入指令,如 FFRRF3R,F就是前进,R就是向右转,2R就是RRR。输出这个指令之后所处的位置。
follow2:在指令里面会出现2(FFR)这种情况,就是FFRFFR。
类似:
然后是那道以前出现过的3[abc2[x]]解码变成abcxxabcxxabcxx。说明了原字符串不会有数字出现.
Answer:
public class TurtleDirection {
//3[abc2[x]] :解码变成abcxxabcxxabcxx
/* Simple version:
public String depressStr(String str, int start){
String res = "";
int digit = 0;
for(int i=start;i<str.length();i++){
if(Character.isDigit(str.charAt(i))){
digit = digit*10 + str.charAt(i) - '0';
}else if(str.charAt(i) >= 'a' && str.charAt(i) <= 'z'){
res += str.charAt(i);
}else if(str.charAt(i) == '['){
String nextLevelStr = depressStr(str, i+1);
for(int k=0;k<digit;k++){
res += nextLevelStr;
}
//!important!
break;
}else if(str.charAt(i) == ']'){
}
}
return res;
}
*/
//变种: 3[abc2[x]d]ef :解码变成abcxxdabcxxdabcxxdef
//1.Recursive:
public String depressStr(String str, int start){
String res = "";
int digit = 0;
int count = 0;
for(int i=start;i<str.length();i++){
if(Character.isDigit(str.charAt(i))){
if(count==0){
digit = digit*10 + str.charAt(i) - '0';
}
}else if(str.charAt(i) >= 'a' && str.charAt(i) <= 'z'){
if(count==0){
res += str.charAt(i);
}
}else if(str.charAt(i) == '['){
if(count==0){
String nextLevelStr = depressStr(str, i+1);
for(int k=0;k<digit;k++){
res += nextLevelStr;
}
}
count++;
}else if(str.charAt(i) == ']'){
//if ']' is matched the '[' level, important recursive end here!
if(count == 0){
return res;
}
count--;
}
}
return res;
}
//2. Using Stack! No recursive!
//3[abc2[x]] :解码变成abcxxabcxxabcxx or 3[abc2[x]d]ef :解码变成abcxxdabcxxdabcxxdef
/*
public String depressStr(String str){
Stack<String> strStack = new Stack<>();
Stack<Integer> numStack = new Stack<>();
String currLevelStr = "";
int digit = 0;
for(int i=0;i<str.length();i++){
if(Character.isDigit(str.charAt(i))){
digit = digit*10 + str.charAt(i) - '0';
}else if(str.charAt(i) >= 'a' && str.charAt(i) <= 'z'){
currLevelStr += str.charAt(i);
}else if(str.charAt(i) == '['){
strStack.add(currLevelStr);
numStack.add(digit);
currLevelStr = "";
digit = 0;
}else if(str.charAt(i) == ']'){
int currLevelNum = numStack.pop();
String tmp = strStack.pop();
if(currLevelNum != 0){
for(int k=0;k < currLevelNum;k++){
tmp += currLevelStr;
}
}else{
tmp += currLevelStr;
}
currLevelStr = tmp;
}
}
return currLevelStr;
}
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TurtleDirection obj = new TurtleDirection();
//String str = "3[abc2[x]]";
String str = "3[abc2[x]d]ef";
System.out.println(obj.depressStr(str,0));
}
}
No comments:
Post a Comment