Java 字符串中单词重复的计数
机器人可以在飞机上向四个方向移动:U-向上、D-向下、L-左、R-右。流量示例为UUDLR、DLRUD。我必须实现“行走”方法,以便它在通过指定路径后返回机器人位置。所以我这样做:Java 字符串中单词重复的计数,java,string,find,counting,word,Java,String,Find,Counting,Word,机器人可以在飞机上向四个方向移动:U-向上、D-向下、L-左、R-右。流量示例为UUDLR、DLRUD。我必须实现“行走”方法,以便它在通过指定路径后返回机器人位置。所以我这样做: class Main { static int[] walk(String path) { int[] A = {0,0}; char charFromPath; for (int i = 0 ; i < path.length() ; i++) { charFromPath = path.c
class Main {
static int[] walk(String path) {
int[] A = {0,0};
char charFromPath;
for (int i = 0 ; i < path.length() ; i++) {
charFromPath = path.charAt(i);
if(charFromPath == 'U')
{
A[1]++;
}
if(charFromPath == 'D')
{
A[1]--;
}
if(charFromPath == 'L')
{
A[0]--;
}
if(charFromPath == 'R')
{
A[0]++;
}
}
return A;
}
public static void main(String[] args) {
{
String path="UUDLR";
int[] position = walk(path);
System.out.println("case 1 - path "+path+ " position 0,1");
if(position[0]==0 && position[1]==1)
System.out.println("the robot went right");
else
System.out.println("the robot smashed");
}
{
String path="DLRUD";
int[] position = walk(path);
System.out.println("\ncase 2 - path "+path+ " position 0,-1");
if(position[0]==0 && position[1]==-1)
System.out.println("the robot went right");
else
System.out.println("the robot smashed");
}
}}
主类{
静态int[]遍历(字符串路径){
int[]A={0,0};
char-charFromPath;
对于(int i=0;i
现在在版本2中根据逻辑U、D、L、R,命令是从左到右的。交通示例为UPUPLEFTRIGHTUP
现在,在版本3中,命令是3xUP 2xLEFT-DOWN-RIGHT。3xUP表示向上移动三次,2xLEFT表示向左移动两次。为机器人添加移动限制,他不能离开10x10区域(项目10.10或-10,-10是最后一个有效值)
我不知道怎么写。如何计算字符串中重复字符串的数量?对于版本2,您可以拆分原始字符串并将其放入一个数组中,方法可以调用字符串
string[]tmpsplit=tmp.split(“”)代码>。这样,您的阵列在每个单元格内都有一个方向(向上或向下或向左或向右)
然后,您可以将此数组放入与版本1类似的for中。用tmpsplit[i]替换charFromPath=='U'
。等于(“UP”)
您可以尝试以下操作
String str = "UPUPLEFTRIGHTUP";
int countUP = ( str.split("UP", -1).length ) - 1;
int countLEFT = ( str.split("LEFT", -1).length ) - 1;
int countRIGHT = ( str.split("RIGHT", -1).length ) - 1;
int countDOWN = ( str.split("DOWN", -1).length ) - 1;
可以通过比较int
值与框的限制来验证限制(10*10
)对于位置,如果我们假设每个运动为1个单位,则:
int x = 0; //starting point in Ox axis
int y = 0; //starting point in Oy axis
x = countRIGHT - CountLeft;
y = countUP - CountDOWN;
这对(x,y)
是机器人的位置。
移动功能:
检查答案,并告诉我您是否需要更多帮助,以及它是否回答了您的问题。我不太明白:(.我如何使用此功能?我不太明白:(.我如何使用此功能?用于什么版本?@141_MATRIX_141;如果您有时间,可以使用函数“walk”吗?编辑了我的答案。你可以这样称呼它:
walk(“UPUPLEFTRIGHTUP”);
在你的主函数中。没问题:)@141_MATRIX_141对于第三个版本,你应该使用常规表达式。你能不能继续写下去,因为我不明白它/
int[] walk(String path) {
int[] position = {0,0};
int countUP = ( path.split("UP", -1).length ) - 1; //Counts how many UP command
int countLEFT = ( path.split("LEFT", -1).length ) - 1; //Counts how many LEFT command
int countRIGHT = ( path.split("RIGHT", -1).length ) - 1; //Counts how many RIGHT command
int countDOWN = ( path.split("DOWN", -1).length ) - 1; //Counts how many DOWN command
position[0] = countRIGHT - countLEFT;
position[1] = countUP - countDown;
return position;
}