May 10th

#include <string>
#include <iostream>
using namespace std;

/*
  Write a function that takes in a string and returns the length of the longest
  prefix in which all characters are arranged in alphabetical order.
  Examples:
    alphaprefix("ransom") = 1
    alphaprefix("google") = 3
    alphaprefix("knotty") = 6
*/

int alphaprefix(string input) {
  if(input.size() <= 1) return input.size();
  int maxLen = 1;
  int len = 1;
  for(int i = 1; i < input.size(); ++i) {
    if(input[i] >= input[i-1]) len++;
    else break;
  }
  return len;
}

int main(void) {
  cout << alphaprefix("ransom") << endl;
  cout << alphaprefix("google") << endl;
  cout << alphaprefix("knotty") << endl;
}

This one is very similar to LeetCode's recover IP Address question, but much simpler! 

#include <iostream>
#include <vector>
using namespace std;

/*
  You are given a int[N] array num, count how many triplets(x, y, z) that
  num[x] + num[y] +  num[z] < K
  Assuming x < y < z
  For example:
  num[] = {5, 3, 6, 1, 8, 10}, K = 13
  5 + 3 + 1 = 9 < 13
  5 + 6 + 1 = 12 < 13
  3 + 6 + 1 = 10 < 13
  3 + 1 + 8 = 12 < 13 ----> return 4.
*/

int countTriplets(vector<int>& nums, int K) {
  if(nums.size() < 3) return 0;
  int count = 0;
  for(int i = 0; i < nums.size() - 2; ++i) {
    int target = nums[i];
    for(int j = i + 1; j < nums.size() - 1; ++j) {
      target += nums[j];
      for(int k = j + 1; k < nums.size(); ++k) {
        target += nums[k];
        if(target < K) {
          count++;
        }
        target -= nums[k];
      }
      target -= nums[j];
    }
  }
  return count;
}

// Thought about it a bit. It seems that sort the nums doesn't actually affect the result.
// The interviewer only asked for the final number. when we chose 3 numbers, they will always
// have x < y < z
int sortCountTriplets(vector<int>& nums, int K) {
  if(nums.size() < 3) return 0;
  sort(nums.begin(), nums.end());
  int count = 0;
  for(int i = 0; i < nums.size() - 2; ++i) {
    int start = i + 1;
    int end = nums.size() - 1;
    while(start < end) {
      int sum = nums[i] + nums[start] + nums[end];
      if(sum < K) {
        count += end - start;
        start++;
      } else end--;
    }
  }
  return count;
}



int main(void) {
  vector<int> nums{5, 3, 6, 1, 8, 10};
  cout << countTriplets(nums, 13) << endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值