[英]Programming exercise
嗨,我一直在做 Javabat 练习,但我发现自己遇到了这个问题:
如果对于字符串中的所有 'x' 字符,在字符串的后面某处存在一个 'y' 字符,我们会说一个字符串是 xy 平衡的。 所以“xxy”是平衡的,但“xyx”不是。 一个“y”可以平衡多个“x”。 如果给定的字符串是 xy 平衡的,则返回 true。
xyBalance("aaxbby") → true
xyBalance("aaxbb") → false
xyBalance("yaaxbb") → false
public boolean xyBalance(String str) {
if(str.length() < 2){
if(str == "x"){
return false;
}
return true;
}
for (int i = 0 ; i < str.length()- 1;i++){
if (str.charAt(i)=='x' && str.charAt(i + 1) == 'y'){
return true;
}
}
return false;
}
x
的 positiony
的positionxPos < yPos
。 (我会留下特殊情况,例如如果没有找到x
或没有y
作为另一个练习;-)
public boolean xyBalance(String str) {
if(!str.contains("x")) { return true; }
int x = str.lastIndexOf("x");
int y = str.lastIndexOf("y");
return x < y;
}
从上到下:如果字符串中没有x,则必须平衡所以返回true。 获取 x 的最后一个实例。 获取 y 的最后一个实例。 如果最后一个 x 在最后一个 y 之前,则返回 true,否则返回 false。
这是我能想到的最简单、最干净的方法。
这是一种使用 charAt() 和迭代循环来解决此问题的方法:
public boolean xyBalance(String str) {
//start from the end of the string
for (int i = str.length()-1;i>=0;i--)
{
if (str.charAt(i) == 'x')
{
//starting from the index of the last 'x', check the rest of the string to see if there is a 'y'
for (int j = i; j < str.length(); j++)
{
if (str.charAt(j) == 'y')
{
//balanced
return true;
}
}
//no 'y' found so not balanced
return false;
}
}
//no 'x' found at all so we are balanced
return true;
}
一旦在给定的字符串中找到一个'x'
后跟一个'y'
,您的方法就会立即返回 true。 因此,在大多数情况下,它会给您的原始问题提供不正确的结果。
我没有给你完整的解决方案,只是一个提示,让你真正学会自己解决问题。 基本上,您需要确定在最后一次出现'x'
之后字符串中是否有'y'
' 。 为此,请使用String.lastIndexOf
。
你的逻辑是有缺陷的:只要你找到一个 x 后跟一个 y,你就会返回 true(即结束循环并给出结果)。 这不是程序应该做的。
此外,如果字符串长度小于 2,则您将字符串与 == 进行比较。 这将比较引用(指针)而不是字符串的内容。 使用 s1.equals(s2) 比较两个字符串的内容。
这是我将如何编写算法(使用 indexOf 的其他解决方案可能更有效,但它们不使用循环。如果您想继续使用循环,这个解决方案应该可以工作)。
balanced
为真 public boolean xyBalance(String str) {
//intialize x and y value to 0
int x = 0;
int y = 0;
//run a for loop and check for x value
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'x') {
//if condition is true increment x value
x++;
//now run a for loop for y only if x condition is true , here it will run from "i" position where we got x value
for (int j = i; j < str.length(); j++) {
if (str.charAt(j) == 'y') {
//once we get value which matches 'y' increment y and break from here so that it will not count more 'y'
y++;
break;
}
}
}
}
//after this check x and y count
if (x == y) {
return true;
} else {
return false;
}
}
我的解决方案:
public static boolean xyBalance(String str) {
boolean xBefore = false;
boolean yAfter = false;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i)=='x') {
xBefore = true;
yAfter = false;
}
if (str.charAt(i)=='y') {
xBefore = false;
yAfter = true;
}
}
if (yAfter || xBefore==false) {
return true;
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.