首页 > 试题广场 >

发送指令跟随坐标移动

[编程题]发送指令跟随坐标移动
  • 热度指数:1098 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解

假设点P处于坐标轴原点,W表示向上,A表示向左,S表示向下,D表示向右,输入一串指令代表P点的移动轨迹,输出最终P的位置

例如 "2W2D"表示向上移动两个坐标位置,再向右移动两个坐标位置

"W2D"表示向上移动一个坐标位置,再向右移动两个坐标位置

示例1

输入

"2W2D"

输出

[2,2]
正则表达式求解,把带数字的和不带数字的操作都匹配出来再进行移动(这题很坑,大小写的字母都有)
class Solution:
    def GetEndPoint(self , order ):
        # write code here
        import re
        x, y = 0, 0
        order = order.upper()
        for match in re.findall("\d+[A-Z]", order):
            if match.endswith("W"):
                y += int(match[:-1])
            elif match.endswith("S"):
                y -= int(match[:-1])
            elif match.endswith("A"):
                x -= int(match[:-1])
            elif match.endswith("D"):
                x += int(match[:-1])
        for match in re.findall("(?<![0-9])[A-Z]+", order):
            for direction in match:
                if direction.endswith("W"):
                    y += 1
                elif direction.endswith("S"):
                    y -= 1
                elif direction.endswith("A"):
                    x -= 1
                elif direction.endswith("D"):
                    x += 1
        return [x, y]

编辑于 2021-09-24 12:22:28 回复(0)
其实吧,有个很大的 疑惑,大家是如何读出来这个方向不只有大写字母呢。。。。
题里面好像似乎没说吧。裂开;
import java.util.*;
public class Solution {
    int X=0,Y=0;
    public int[] GetEndPoint (String order) {
        int index = 0;
         
        while(index<order.length()){
            int start = index;
            int end = start;
            while(end<order.length() && Character.isDigit(order.charAt(end))){
                end++;
                index++;
            }
            int tmp;
            if(start==end)tmp=1;
            else{
                tmp=Integer.parseInt(order.substring(start,end));
                System.out.println(tmp);
            }
            char c1 = order.charAt(index);
            if(c1=='A'||c1=='a'){
                X-=tmp;
            }else if(c1=='D'||c1=='d'){
                X+=tmp;
            }else if(c1=='S'||c1=='s'){
                Y-=tmp;
            }else if(c1=='W'||c1=='w'){
                Y+=tmp;
            }
            index++;
        }
        return new int[]{X,Y};
    }
}


发表于 2022-07-28 14:00:11 回复(0)
比较简洁的做法,建立一个以字符为key的map,忽略大小写
需要的数据结构:忽略大小字符的map;n(n为0时,表示字符前没有数字,对应的value加1:n不为0时,表示前面有数字,对应的key加n)
核心思想是:遍历
- 如果碰到数字了,就保存下来,最后组成一个整数;
- 如果是字符,就看前面有没有保存数字(判断n的值),n为0的话value加1,否则对应的value加n,最后清楚n(令n = 0)

class Solution {
public:
    struct cmp{
        bool operator()(const char& a,const char& b){
            return tolower(a) < tolower(b);
        }
    };
    vector<int> GetEndPoint(string order) {
        // write code here
        int x = 0, y = 0;
        int n = 0;
        map<char,int, cmp> memo;
        for(int i = 0; i < order.size(); i++){
            if(order[i] >= '0' && order[i] <= '9')
                n = n*10 +order[i] -'0';
            else {
                memo[order[i]] += n == 0 ? 1 : n;
                n = 0;
            }
        }
        return {memo['D'] - memo['A'],memo['W'] - memo['S']};
    }
};


发表于 2022-01-19 22:19:51 回复(0)
classSolution {
public:
    vector<int> GetEndPoint(string order) {
       vector<int> ans={0,0};
        intt=0;
        for(charc:order){
            if(c=='A'||c=='a'){if(t)ans[0]-=t;
                       elseans[0]--;t=0;}
            elseif(c=='W'||c=='w'){if(t)ans[1]+=t;
                       elseans[1]++;t=0;}
            elseif(c=='S'||c=='s'){if(t)ans[1]-=t;
                       elseans[1]--;t=0;}
            elseif(c=='D'||c=='d'){if(t)ans[0]+=t;
                       elseans[0]++;t=0;}
            elset=10*t+c-'0';
        }returnans;
    }
};
发表于 2022-08-22 15:57:00 回复(0)
func GetEndPoint(order string) []int {
	if len(order) == 0 {
		return []int{0, 0}
	}
	num := 1
	x, y := 0, 0
	r := 0
	for r < len(order) {
		if order[r]-'0' <= 9 {
			num = 0
			for order[r]-'0' <= 9 {
				num = num*10 + int(order[r]-'0')
				r++
			}
		} else {
			if order[r] == 'd' || order[r] == 'D' {
				x += num
			}
			if order[r] == 'w' || order[r] == 'W' {
				y += num
			}
			if order[r] == 'a' || order[r] == 'A' {
				x -= num
			}
			if order[r] == 's' || order[r] == 'S' {
				y -= num
			}
			r++
			num = 1
		}
	}
	return []int{x, y}
}

发表于 2022-07-19 17:17:28 回复(1)
没什么难度就是统计加减坐标就行,关键就是有大小写的问题!
已经不是第一次遇到这种问题了呵呵,直接干掉!
发表于 2022-07-02 12:11:17 回复(0)
就正常的从左到右判断
如果指向的是数字就向右搜索到完整数字为止,匹配上数字后的第一个字母进行移动
如果指向的是字母,就移动一步即可
注意方向可以是大写字母,也可以是小写字母!!!!!
// 解析字符串
// 数字+字母
// 字母+字母

import java.util.*;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param order string字符串 
     * @return int整型一维数组
     */
	
	private int x = 0;
	private int y = 0;
	
    public int[] GetEndPoint (String order) {
        // write code here
		char[] arr = order.toCharArray();
		int id = 0;
		while(id < arr.length) {
			if (isNum(arr[id])) {
				int end = id;
				while (end < arr.length && isNum(arr[end])) {end++;}
				move(Integer.parseInt(order.substring(id, end)), arr[end]);
				id = end+1;
			} else {
				move(1, arr[id]);
				id += 1;
			}
		}
		return new int[] {x, y};
    }
	
	private boolean isNum(char a) {
		if (a >= '0' && a <= '9') {
			return true;
		}
		return false;
	}
	
	private void move(int step, char d) {
		
		switch (d) {
			case 'W' : y+=step;
			break;
			case 'A' : x-=step;
			break;
			case 'D' : x+=step;
			break;
			case 'S' : y-=step;
			break;
			case 'w' : y+=step;
			break;
			case 'a' : x-=step;
			break;
			case 'd' : x+=step;
			break;
			case 's' : y-=step;
			break;
		}
	}
}


发表于 2022-06-07 11:44:13 回复(0)
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param order string字符串 
     * @return int整型一维数组
     */
    public int[] GetEndPoint (String order) {
        order = order.toUpperCase();
        // write code here
        int[] ans = new int[]{0, 0};
        int num = 0;
        Character dir = null;
        for(int i = 0; i < order.length(); i++){
            //if(num == 0 && dir != null) continue;
            if(order.charAt(i) >= '0' && order.charAt(i) <= '9'){
                num = num * 10 + order.charAt(i) - '0';
            }else{
                if(num == 0) num = 1;
                dir = order.charAt(i);
                if(dir == 'W') ans[1] += num;
                else if(dir == 'S') ans[1] -= num;
                else if(dir == 'A') ans[0] -= num;
                else ans[0] += num;
                num = 0;
                dir = null;
            }
        }
        return ans;
    }
}

发表于 2022-04-11 17:20:13 回复(0)
我晕了。方向向上我一直都以为是将横坐标增加,没有和坐标轴对应上。
import java.util.*;


public class Solution {
    public int[] GetEndPoint (String order) {
        if (order == null) {
            return new int[]{0, 0};
        }
        char[] cs = order.toCharArray();
        int[] point = {0, 0};
        Map<Character, int[]> map = new HashMap<Character, int[]>(){{
            put('D', new int[]{1, 0});
            put('S', new int[]{0, -1});
            put('A', new int[]{-1, 0});
            put('W', new int[]{0, 1});
            put('d',new int[]{1, 0});
            put('s', new int[]{0, -1});
            put('a', new int[]{-1, 0});
            put('w', new int[]{0, 1});
        }};
        int n = cs.length;
        int last = 1;
        for (int i = 0; i < n; i++) {
            if (cs[i] >= '0' && cs[i] <= '9') {
                int j = i, res = 0;
                while (cs[j] >= '0' && cs[j] <= '9') {
                    res = res * 10 + (cs[j] - '0');
                    j++;
                }
                last = res;
                i = j - 1;
            } else {
                int[] next = map.get(cs[i]);
                point[0] += next[0] * last;
                point[1] += next[1] * last;
                //防止没有last的情况。
                last = 1;
            }

        }
        return point;
    }
}


发表于 2022-03-28 21:17:05 回复(0)
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param order string字符串 
 * @return int整型一维数组
 * @return int* returnSize 返回数组行数
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
int* GetEndPoint(char* order, int* returnSize ) {
    // write code here
    int x = 0, y = 0, t = 0;
    for(int i = 0; i < strlen(order); i++){
        if(!(order[i] == 'W' || order[i] == 'w') && !(order[i] == 'S' || order[i] == 's') && !(order[i] == 'A' || order[i] == 'a') && !(order[i] == 'D' || order[i] == 'd')){
            t += order[i]-'0';
            t *= 10;
            printf("i=%d t=%d\n",i,t/10);
        }else{
            if(t == 0)t = 10;
            if(order[i] == 'W' || order[i] == 'w'){
                y = y + t/10;
            }else if(order[i] == 'S' || order[i] == 's'){
                y = y - t/10;
            }else if(order[i] == 'A' || order[i] == 'a'){
                x = x - t/10;
            }else{
                x = x + t/10;
            }
            t = 0;
            printf("x=%d y=%d\n", x, y);
        }
    }
     
    int* res = (int*)malloc(sizeof(int)*2);
    res[0] = x;
    res[1] = y;
    *returnSize = 2;
    return res;
}

发表于 2022-03-07 08:30:33 回复(0)
通过全部测试用例,注意点:字母可能小写、数字可能大于9
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param order string字符串 
     * @return int整型vector
     */
    vector<int> GetEndPoint(string order) {
        // write code here
        vector<int> res;
        bool flag = false;  // 如果为true表示某动作前面有数字
        int start = -1;  //数字第一次出现的位置
        Point p;
        p.x = 0;
        p.y = 0;
        for(int i=0; i<order.size(); i++)
        {
            if(isdigit(order[i])){  //当前为数字
                if(flag){  // 前面已经也是数字了
                    continue;
                }
                else{  // 第一次出现数字
                    start = i;
                    flag = true;
                }
            }
            else{  // 当前为字母
                char c = toupper(order[i]);  // 小写字母转换成大写
                switch(c)
                {
                   case 'W':  // 上
                       if(flag){
                            string temp = order.substr(start, i-start);
                            p.y += stoll(temp);
                            flag = false;
                       }
                       else{
                            p.y += 1;
                       }
                       break;
                   case 'S':  // 下
                       if(flag){
                            string temp = order.substr(start, i-start);
                            p.y -= stoll(temp);
                            flag = false;
                       }
                       else{
                            p.y -= 1;
                       }
                       break;
                   case 'A':  // 左
                       if(flag){
                            string temp = order.substr(start, i-start);
                            p.x -= stoll(temp);
                            flag = false;
                       }
                       else{
                            p.x -= 1;
                       }
                       break;
                   case 'D':  // 右
                       if(flag){
                            string temp = order.substr(start, i-start);
                            p.x += stoll(temp);
                            flag = false;
                       }
                       else{
                            p.x += 1;
                       }
                       break;
               }
            }
        }
        res.push_back(p.x);
        res.push_back(p.y);

        return res;
    }
};


发表于 2021-12-17 15:36:06 回复(0)
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param order string字符串 
     * @return int整型vector
     */
    inline int checkdigit(char s){
        if(s>='0'&&s<='9') return s-'0';
        return -1;
    }
    vector<int> GetEndPoint(string order) {
        // write code here
        int stepLength = 0;
        int orderLength = order.size();
        int x=0, y=0;
        
        for(char i:order){
            if(checkdigit(i)<0){
                if(stepLength == 0) stepLength=1;
                if(i == 'W'){
                    y+=stepLength;
                }else if(i == 'D'){
                    x+=stepLength;
                }else if(i == 'S'){
                    y-=stepLength;
                }else{
                    x-=stepLength;
                }
                stepLength = 0;
            } else {
                stepLength = stepLength*10 + checkdigit(i);
            }
        }
        return {x,y};
    }
};

这破题根本不给变量范围没法debug。。通过5/10

发表于 2021-09-16 01:04:42 回复(3)
import java.util.*;
 
 
public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param order string字符串
     * @return int整型一维数组
     */
    public int[] GetEndPoint (String order) {
        char[] orders=order.toCharArray();
        int A=0;
        int D=0;
        int W=0;
        int S=0;
        int[] res=new int[2];
        if(orders.length==0){
            return res;
        }
        int sum=0;
        for(inti=0;i<orders.length;i++){
            if(orders[i]!='A'&&orders[i]!='D'&&orders[i]!='W'&&orders[i]!='S'){
                sum*=10;
                sum+=(orders[i]-'0');
            }else{
                if(orders[i]=='A'){
                    if(sum==0){
                        A-=1;
                    }else{
                        A-=sum;
                        sum=0;
                    }
                }
                if(orders[i]=='D'){
                    if(sum==0){
                        D+=1;
                    }else{
                        D+=sum;
                        sum=0;
                    }
                }
                if(orders[i]=='W'){
                    if(sum==0){
                        W+=1;
                    }else{
                        W+=sum;
                        sum=0;
                    }
                }
                if(orders[i]=='S'){
                    if(sum==0){
                        S-=1;
                    }else{
                        S-=sum;
                        sum=0;
                    }
                }
            }//else      
        }//for
        res[0]=numOfW+numOfS;
        res[1]=numOfA+numOfD;
        return res;
    }
}
大佬们,我这写的为什么只过了2/10的用例啊?

发表于 2021-08-27 17:18:27 回复(5)