您的位置:首页 > Web前端

牛客网offer直通

2016-04-19 22:15 351 查看

问题



错误代码

一个case都没过,好惨有木有

public String trans (String s, int n) {
if (n == 0) return "";
String [] content = s.split(" ");
String result = "";
for (int i = 0; i < content.length;i++) {
content[i] = exChange(content[i]);
if (i == 0) {
result = content[i];
} else {
result = content[i] + " " + result;
}
}
return result;
}

public String exChange (String str) {
StringBuffer sb = new StringBuffer();
if(str != null) {
for(int i = 0;i < str.length(); i++){
char c = str.charAt(i);
if(Character.isUpperCase(c)){
sb.append(Character.toLowerCase(c));
}else if(Character.isLowerCase(c)){
sb.append(Character.toUpperCase(c));
}
}
}
return sb.toString();
}

public static void main (String [] args) {
//        "h i ",4
TransformO tfo = new TransformO();
System.out.println(tfo.trans("h i ",4));
}


一直说通过率0.00%,感觉是题目理解错了。应该是把连续的空格全变成一个,开头结尾空格直接去掉。

哭晕。。。。

后来知道根本不是这样

错误原因

这题题意不清楚的很啊,要是清楚所有人都能水过了。。。

看这三个:

" This is a sample " => " SAMPLE A IS tHIS "
" this" => "THIS "
"this "=>" THIS"


这题难在空格啊,真是细节问题整死人。。。

正确代码

package cn.mitsuhide.Algorithm.newCoder;

/**
* Created by zly on 2016/4/27.
*/
public class Transform {
public String trans (String s, int n) {
if (n == 0) return "";

String result = "";

int expect = 1;
int i = 0;
int length = s.length();
while (i < length) {
while (i < length && s.charAt(i) == ' ') {
result = " " + result;
i++;
}

if (i >= length) {
return result;
}

String temp = "";
char ch = s.charAt(i);
while (i < length && ch != ' ') {
if (ch >= 'A' && ch <= 'Z') {
ch += 32;
} else if (ch >= 'a' && ch <= 'z') {
ch -= 32;
}
temp += ch;
i++;
if (i < length) {
ch = s.charAt(i);
}
}
result = temp + result;
}
return result;
}

public static void main (String [] args) {
Transform ts = new Transform();
System.out.println(ts.trans("h i ", 4));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: