华为3.30机试记录
经验:
- 做题的时候应该先从小题入手,估计40分钟到1小时应该就能稳拿100分;
考试时候先做了大题,花费了较多的时间,导致最简单的一道简单题,没有充分的时间去做。 - 最好在早上或者下午时候做,我是晚上9点多开始,脑子想的太多了,思维太混乱,导致不能够清楚地分析题目,可能与时间点是有关系的吧
- 输入两串字符串,检验第一个字符串是否为第二个字符串的子串(子串出现的顺序在父串中是相同的)
如果是子串,输出子串中最后一个字符在父串中最后一次出现的位置
eg1: ace->abcde 输出5,因为ace中的字符全部出现在abcde中,而且e在父串中最后一个位置是5
eg2: acf->abcde 输出-1;
eg3: ab -> bacd 输出-1;
eg4: ab -> babcd 输出2;Solution one
public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s; while ((s = br.readLine()) != null) { char[] strs = s.toCharArray(); String string = br.readLine(); int res = -1; Map map = new HashMap(strs.length); //先将s的所有字符从string里查到存到map,查不到就存-1 for (char str : strs) { int index = string.lastIndexOf(String.valueOf(str)); if (!map.containsKey(str)) { map.put(str, index); } } if (strs.length == 1) { res = map.get(strs[strs.length - 1]); } else { //遍历s的每一个字符,到最后一个,如果获取到的index等于-1或者小于前一个值的index,输出-1 if ((map.get(strs[0]) != -1)) { for (int i = 1; i < strs.length; i++) { if ((map.get(strs[i]) < map.get(strs[i - 1])) || map.get(strs[i]) == -1) { break; } else { res = map.get(strs[strs.length - 1]); } } } } System.out.println(res); } }
Solution two
private static int getChild(String father, String child) { char[] charChild = child.toCharArray(); HashMap<Character, Integer> map = new HashMap<>(); for (char c : charChild) { if (!father.contains(String.valueOf(c))) { return -1; } else { for (Integer value : map.values()) { if (father.lastIndexOf(c) < value) { return -1; } } map.put(c, father.lastIndexOf(c)); } } return map.get(child.charAt(child.length() - 1)); }