zoukankan      html  css  js  c++  java
  • Leetcode 318 Maximum Product of Word Lengths 字符串处理+位运算

    先介绍下本题的题意:

    在一个字符串组成的数组words中,找出max{Length(words[i]) * Length(words[j]) },其中words[i]和words[j]中没有相同的字母,在这里字符串由小写字母a-z组成的。

    对于这道题目我们统计下words[i]的小写字母a-z是否存在,然后枚举words[i]和words[j],找出max{Length(words[i]) * Length(words[j]) }。

    小写字母a-z是26位,一般统计是否存在我们要申请一个bool flg[26]这样的数组,但是我们在这里用int代替,int是32位可以替代flg数组,用 与(&),或(1),以及向左移位(<<)就能完成。如“abcd” 的int值为 0000 0000 0000 0000 0000 0000 0000 1111,“wxyz” 的int值为 1111 0000 0000 0000 0000 0000 0000 0000,这样两个进行与(&)得到0, 如果有相同的字母则不是0。

     1 class Solution {
     2 public:
     3     int maxProduct(std::vector<std::string>& words) 
    {
    4 std::vector<int> flg_;
    5 for (std::vector<std::string>::size_type i = 0; i < words.size(); ++i){ 6 int tflg_ = 0; 7 for (std::string::size_type j = 0; j < words[i].size(); ++j){ 8 tflg_ |= (1 << (words[i][j] - 'a')); // 对于'a' 就是 1 而对于‘b’是 10 'c'是100 9 } 10 flg_.push_back(tflg_); 11 }
    12 int ans = 0; 13 for (std::vector<int>::size_type i = 0; i < flg_.size(); ++i){ 14 for (std::vector<int>::size_type j = i + 1; j < flg_.size(); ++j){ 15 if ((flg_[i] & flg_[j]) == 0) ans = std::max(ans, (int)(words[i].size() * words[j].size()));//words[i]和words[j]中没有相同的字母 16 } 17 }
    18 return ans; 19 } 20 };
  • 相关阅读:
    percona_xtrabackup
    利用java实现的一个发送手机短信的小例子
    使用mybatis执行oracle存储过程
    oracle 存储过程 基础
    oracle存储过程常用技巧
    oracle存储过程、声明变量、for循环|转|
    Oracle 存储过程
    mybatis 调用存储过程 返回游标 实例
    Spring Aop实例
    Struts2之自定义类型转换器
  • 原文地址:https://www.cnblogs.com/onlyac/p/5155881.html
Copyright © 2011-2022 走看看