C/C++教程

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

本文主要是介绍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白人 头晕脑胀的三道简单算法题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!