日常水题,刷刷!!!
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
/**
* 题意:输入字符串,删除其中一些字符,如果字符可以变为 hello ,则输出 YES , 否则输出 NO
*
* @author TinyDolphin
* 2017/6/24 14:25.
*/
public class Main {
/**
* 判断数组是否有序,且相邻元素不相等(arr[n] > arr[n-1])
*
* @param arr 待判断数组
* @return 若数组有序,返回 true,否则返回 false
*/
public static boolean isSort(int[] arr) {
for (int index = 1; index < arr.length; index++) {
if (arr[index] <= arr[index - 1]) {
return false;
}
}
return true;
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
String inputWord;
int[] location = new int[5];
while (in.nextToken() != StreamTokenizer.TT_EOF) {
inputWord = in.sval;
location[0] = inputWord.indexOf("h", 0);
location[1] = inputWord.indexOf("e", location[0] + 1);
location[2] = inputWord.indexOf("l", location[1] + 1);
location[3] = inputWord.indexOf("l", location[2] + 1);
location[4] = inputWord.indexOf("o", location[3] + 1);
out.println(isSort(location) ? "YES" : "NO");
}
out.flush();
}
}
做出以下优化,减少代码量。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
/**
* 题意:输入字符串,删除其中一些字符,如果字符可以变为 hello ,则输出 YES , 否则输出 NO
*
* @author TinyDolphin
* 2017/5/27 14:25.
*/
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
String inputWord;
String hello = "hello ";//注意此处,最后需要多一个字符,如空格
while (in.nextToken() != StreamTokenizer.TT_EOF) {
inputWord = in.sval;
int indexJ = 0;
for (int indexI = 0; indexI < inputWord.length(); indexI++) {
if (inputWord.charAt(indexI) == hello.charAt(indexJ)) {
indexJ++;
}
}
out.println(indexJ == 5 ? "YES" : "NO");
}
out.flush();
}
}