Apple screening carlos白人 头晕脑胀的三道简单算法题

find index without indexOf()

//foor loop in the collection

for (int i = 0; i < s.length(); i++) {
  for (int j = i + 1; j < s.length() - i; j++) {
    //get substring from (i,j)
    String s = s.substring(i,j);
    if (s.equals(target)){
      rerturn i;
    }
    }
  }


for (int i = 0; i < s.length() - target.length(); i++) {
  String str = s.substring(i, i + target.length());
  if (s.equals(target)){
      rerturn i;
  }
}

sort
public String sort(String input, String order) {
  //count characters from the input string
  int count[] = new int[26];
  for (int i = 0; i < input.length(); i++) {
    count[input[i] - 'a']++;
  }

  //sort according to 'order' string, add to the result char array
  int index = 0;
  //char[] result = new char[26];
  StringBuilder resultSb = new StringBuilder();

  for (int j = 0; j < order.length(); j++) {
    for (int k = 0; k < count[order.charAt(j) - 'a']; k++) {
      //result[index++] = order.charAt(j);
      resultSb.append(order.charAt(j));
    }
  }

   //add a comparasion between result string and input string, append extra input string if necessary
   //change the input string to char[] for compare
   char[] inputChars = input.toCharArray();
   for (char c : inputChars) {
      if (!resultSb.toString().contains(c)) {
        resultSb.append(c);
      }
   }

   return resultSb.toString();

}

//2 for loops
//1 for loop + hashmap

public boolean findCombination(int[] nums, int target) {
  HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
  int res = false;

  //judge wheter the 'target - nums[i]' is key already, if yes, return true, if no, add 'nums[i]' itself as a new key
  for (int i = 0; i < nums.length; i++) {
    if (map.containsKey(target - nums[i]))
      return true;
    else map.put(nums[i]);
  }

  return res;
}

 Apple screening carlos白人 头晕脑胀的三道简单算法题

 

上一篇:Mac OS 10.14安装Navicat显示已损坏无法打开


下一篇:如何检查 AirPods 是否为正品?