Showing posts with label LeetCode String. Show all posts
Showing posts with label LeetCode String. Show all posts

Sunday, November 1, 2015

Implement strStr()

Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.
思路:
1. 暴力解法,复杂度O(M*N).

Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
思路:
1. 必须把字符串统一为小写,而且要忽略除数字和字符外的所有符号。
2. 利用 String.toCharArray() 转换字符串为Character数组。
3. 双指针check头尾,直到双指针相遇前停止,不相等则返回false。
4. 结束check则返回true。

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.
思路:
1. 利用String的split函数,生成包含多个String的数组,注意其中会有空字符串。
2. 从后往前,利用StringBuilder建立反向字符串,注意检查不是空字符串,每次添加空格。
3. 如果StringBuilder为空返回空字符串,否则返回substring(0, sb.length()-1)
4. 输入字符串为空是唯一的特殊情况。