2016/10/31
Reverse Words in a String
Given an input string, reverse the string word by word.
For example,
Given s = “the sky is blue”,
return “blue is sky the”.
Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.
click to show clarification.
Subscribe to see which companies asked this question
Show Tags
Show Similar Problems
class Solution(object):
def reverseWords(self, s):
"""
:type s: str
:rtype: str
"""
strings = s.split()[::-1]
result = ""
for string in strings:
if strings.index(string) != len(strings) - 1:
string += " "
result += string
return result
7. Reverse Integer
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
反转int数,注意int型的取值范围是-2147483648~ 2147483647,小心overflow
Python
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x1 = int(str(x).replace("-","")[::-1])
if (x1 > -2147483648 and x1 < 2147483647 ):
return x1 if x > 0 else -x1
return 0
Java
public class Solution {
public int reverse(int x) {
String s = (x + "").replaceAll("-", "");
String re = new StringBuffer(s).reverse().toString();
int result = 0;
try{
if(x < 0)
result = -Integer.parseInt(re);
else
result = Integer.parseInt(re);
}catch(NumberFormatException e){
return 0;
}
return result;
}
}
Java写得这个Runtime太长了 = =想办法改进。
58. Length of Last Word
Given a string s consists of upper/lower-case alphabets and empty space characters ’ ‘, return the length of last word in the string.
If the last word does not exist, return 0.Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = “Hello World”,
return 5.
Python
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.split()
if len(s) <= 0:
return 0
return len(s[len(s)-1])
Java
public class Solution {
public int lengthOfLastWord(String s) {
String[] strings = s.split(" ");
if(strings.length <= 0)
return 0;
return strings[strings.length-1].length();
}
}
136.Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
一开始的想法是先去重,然后在新列表中append两次去重后的元素,再在新列表中remove旧列表中的元素,用了两次for循环,结果TLE了。后来一想,参数列表的长度是奇数,先排序,再判断首位和末位,再用一次for比较中间元素。
Python
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums = sorted(nums)
if len(nums) == 1:
return nums[0]
if nums[0] != nums[1] and nums[1] == nums[2]:
return nums[0]
if nums[len(nums) - 1] != nums[len(nums) -2] and nums[len(nums)-2] == nums[len(nums)-3]:
return nums[len(nums) - 1]
for i in range(1,len(nums)):
if nums[i] != nums[i - 1] and nums[i] != nums[i + 1]:
return nums[i]
Java
public class Solution {
public int singleNumber(int[] nums) {
Arrays.sort(nums);
if(nums.length == 1)
return nums[0];
if(nums[0] != nums[1] && nums[1] == nums[2])
return nums[0];
if(nums[nums.length - 1] != nums[nums.length - 2] && nums[nums.length - 2] == nums[nums.length - 3])
return nums[nums.length - 1];
for(int i = 1; i < nums.length; ++i){
if(nums[i] != nums[i - 1] && nums[i] != nums[i + 1])
return nums[i];
}
return 0;
}
}
上面两段代码对137 Single Number 2 也适用
290. Word Pattern
Given a pattern and a string str, find if str follows the same pattern.
Python
class Solution(object):
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
str_lst = str.split()
if(len(pattern) != len(str_lst)):
return False
if len(set(str_lst)) != len(set(pattern)):
return False
d = {}
for i in range(0, len(str_lst)):
if pattern[i] in d.keys():
if d[pattern[i]] != str_lst[i]:
return False
d[pattern[i]] = str_lst[i]
return True
Runtime: 35ms
Java
public class Solution {
public boolean wordPattern(String pattern, String str) {
String[] str_lst = str.split(" ");
if(pattern.length() != str_lst.length)
return false;
Set<String> set_lst = new HashSet<String>();
Set<Character> str_set_lst = new HashSet<Character>();
Collections.addAll(set_lst, str_lst);
for(int i = 0; i < pattern.length(); ++i){
str_set_lst.add(pattern.charAt(i));
}
if(set_lst.size() != str_set_lst.size())
return false;
Map<Character, String> d = new HashMap<Character, String>();
for(int i = 0; i < str_lst.length; ++i){
if(d.containsKey(pattern.charAt(i))){
if(!d.get(pattern.charAt(i)).equals(str_lst[i])){
return false;
}
}
d.put(pattern.charAt(i), str_lst[i]);
}
return true;
}
}
Runtime: 3ms
171. Excel Sheet Column Number
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
…
Z -> 26
AA -> 27
AB -> 28
这道题说白了是一个进制转换的问题,27进制。
Python
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
result = 0
trans = 0
j = 0
for i in range(len(s) - 1, -1, -1):
trans = (alpha.index(s[i]) + 1) * (26 ** j)
result += trans
j += 1
return result
Runtime 46ms
Java
public class Solution {
public int titleToNumber(String s) {
String string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int result = 0, j = 0;
for(int i = s.length() - 1; i > -1; --i){
char c = s.charAt(i);
int trans = 0, tmp = 1;
trans = string.indexOf(c) + 1;
for(int k = 0; k < j; ++k)
tmp *= 26;
trans *= tmp;
result += trans;
j += 1;
}
return result;
}
}
Runtime: 3ms
330. Patching Array
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.
这道题没做出来,看了讨论区的有了思路。
先设定一个数miss,表示[0, miss)之间的数。再从数组的第一个数开始,如果小于等于miss,则让miss加上这个数,这样就可以表示[0,miss+nums[i])之间的数了。否则,就加上miss本身。
Python
class Solution(object):
def minPatches(self, nums, n):
"""
:type nums: List[int]
:type n: int
:rtype: int
"""
miss, added, i = 1, 0, 0
while(miss <= n):
if(i < len(nums) and nums[i] <= miss):
miss += nums[i]
i += 1
else:
miss += miss
added += 1
return added
Runtime: 49ms
Java
public class Solution {
public int minPatches(int[] nums, int n) {
long miss = 1;
int i = 0;
int added = 0;
while(miss <= n){
if(i < nums.length && nums[i] <= miss){
miss += nums[i++];
}
else {
miss += miss;
added++;
}
}
return added;
}
}
Runtime: 1ms
Count and Say
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, …
Python
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n == 1:
return "1"
after = self.generator("1")
begin = self.generator("1")
for i in range(0, n - 2):
after = self.generator(begin)
begin = after
return after
def generator(self, begin):
count = 1
result = ""
tmp = begin[0]
for i in range(0, len(begin)):
if i == len(begin) - 1:
return result + str(count) + begin[i]
else:
if tmp == begin[i + 1]:
count += 1
else:
result = result + str(count) + tmp
tmp = begin[i + 1]
count = 1
#69ms
Runtime: 69 ms
Java
public class Solution {
public String countAndSay(int n) {
if(n == 1)
return "1";
String after = generator("1");
String begin = generator("1");
for(int i = 0; i < n - 2; ++i){
after = generator(begin);
begin = after;
}
return after;
}
public static String generator(String begin){
int count = 1;
String result = "";
char tmp = begin.charAt(0);
for(int i = 0; i < begin.length(); ++i){
if(i == begin.length() - 1)
return result + count + begin.charAt(i);
else {
if(tmp == begin.charAt(i + 1)){
count += 1;
}
else {
result = result + count + tmp;
tmp = begin.charAt(i + 1);
count = 1;
}
}
}
return "";
}
}
Runtime: 25ms