2017/11/5 Leetcode 日记

2017/11/5 Leetcode 日记

476. Number Complement

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:

  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.

Solutions:

class Solution {
public:
int findComplement(int num) {
unsigned mask = ~;
while(mask & num) mask <<=;
return ~mask & ~num;
}
};

c++

class Solution:
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
i =
while(i<=num):
i<<=
return (i-)^num

python3

557. Reverse Words in a String III

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Solutions:

class Solution {
public:
string reverseWords(string s) {
int index = , max;
for(int i = ; i < s.size(); i++){
if(s[i] == ' ' || i == s.size()-){
max = i-;
if (i == s.size()-) max = i;
for(int j = index; j < max; j++, max--){
char temp = s[j];
s[j] = s[max];
s[max] = temp;
}
index = i+;
}
}
return s;
}
};

c++

class Solution:
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
a = ' '
s = a.join(x[::-] for x in s.split())
return s

python3

500. Keyboard Row

Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.

2017/11/5 Leetcode 日记

(要你判断能用键盘一行打出来的单词,KeyboardMan必备技能啊)

Solutions:

class Solution {
public:
vector<string> findWords(vector<string>& words) {
unordered_set<char> set1 = {'q', 'w','e', 'r', 't', 'y', 'u', 'i', 'o', 'p'};
unordered_set<char> set2 = {'s', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'a'};
unordered_set<char> set3 = {'z', 'x', 'c', 'v', 'b', 'n', 'm'};
vector<unordered_set<char>> sets = {set1, set2, set3};
vector<string> nes;
for(string& word : words){
int raw = -;
for(int i = ; i<; i++){
if(sets[i].count(tolower(word[])) > )
raw = i;
}
if(raw == -) continue;//除0,1,2外的第四种可能
bool valid = true;
for(int j = , sz = word.size(); j < sz; j++){
if(sets[raw].count(tolower(word[j])) == )
valid = false;
}
if(valid)nes.push_back(word);
}
return nes;
}
};

c++

class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
return filter(re.compile('(?i)([qwertyuiop]*|[asdfghjkl]*|[zxcvbnm]*)$').match, words)

python2

上一篇:2017/11/6 Leetcode 日记


下一篇:2017/11/20 Leetcode 日记