华为OD机试真题-字符串变换最小字符
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int maxCount = Integer.parseInt(in.nextLine());
String word = in.nextLine();
System.out.println(getResult(word, maxCount));
}
public static String getResult(String word, int maxCount) {
StringBuilder wordBuilder = new StringBuilder(word);
int i = 0;
int index = 0;
int left = 0, right = 0;
StringBuilder ans = new StringBuilder();
while (i < wordBuilder.length()) {
if (wordBuilder.charAt(i) == '-') {
index++;
wordBuilder.delete(i, i + 1);
}
if (index == 1) {
ans.append(wordBuilder.substring(0, i) + "-");
left = i;
right++;
i++;
index++;
continue;
} else if (index > 0 && right - left == maxCount){
String temp = wordBuilder.substring(left, right);
change(temp);
ans.append(temp + "-");
left = i;
}
if (i == wordBuilder.length() - 1) {
String temp = wordBuilder.substring(left, wordBuilder.length());
change(temp);
ans.append(temp + "-");
}
right++;
i++;
}
return ans.delete(ans.length()-1, ans.length()).toString();
}
public static void change(String word) {
int low = 0;
int uppper = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) >= 'a' && word.charAt(i) <= 'z')
low++;
else if (word.charAt(i) >= 'A' && word.charAt(i) <= 'Z')
uppper++;
}
if (low > uppper)
word.toLowerCase();
if (uppper > low)
word.toUpperCase();
}
Scanner in = new Scanner(System.in);
int maxCount = Integer.parseInt(in.nextLine());
String word = in.nextLine();
System.out.println(getResult(word, maxCount));
}
public static String getResult(String word, int maxCount) {
StringBuilder wordBuilder = new StringBuilder(word);
int i = 0;
int index = 0;
int left = 0, right = 0;
StringBuilder ans = new StringBuilder();
while (i < wordBuilder.length()) {
if (wordBuilder.charAt(i) == '-') {
index++;
wordBuilder.delete(i, i + 1);
}
if (index == 1) {
ans.append(wordBuilder.substring(0, i) + "-");
left = i;
right++;
i++;
index++;
continue;
} else if (index > 0 && right - left == maxCount){
String temp = wordBuilder.substring(left, right);
change(temp);
ans.append(temp + "-");
left = i;
}
if (i == wordBuilder.length() - 1) {
String temp = wordBuilder.substring(left, wordBuilder.length());
change(temp);
ans.append(temp + "-");
}
right++;
i++;
}
return ans.delete(ans.length()-1, ans.length()).toString();
}
public static void change(String word) {
int low = 0;
int uppper = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) >= 'a' && word.charAt(i) <= 'z')
low++;
else if (word.charAt(i) >= 'A' && word.charAt(i) <= 'Z')
uppper++;
}
if (low > uppper)
word.toLowerCase();
if (uppper > low)
word.toUpperCase();
}
全部评论
相关推荐
11-02 20:23
济南大学 Java 点赞 评论 收藏
分享
10-30 17:07
University of California Riverside UE4 点赞 评论 收藏
分享