leetcode medium

3 Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
View Code

思路1:O(n2)时间复杂度,尺取法,双指针枚举最长子串的开头和结尾,hash判断是否重

思路2:可针对1优化,若(i, j)不重复,而(i, j + 1)重复了(设重复的下标为m, j + 1),那么下一个最长子串只可能从(m + 1)开始,用map记住字符的下标即可。

#### 错误: 不能看到重复就新建map或仅更新该字符 ####

新建会丢失(m + 1, j)之间的信息。 仅更新该字符则会出现与(i ,m)之间重时认为不符合,其实符合 ====> 解决: 此时start 应 > map 取出的数,只在start小的时候更新即可。start = Math.max(start, m.get(s.charAt(end)));

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if (s == null) {
            return 0;
        }
        int start = 0;
        int end = 0;
        int ans = 0;
        Map<Character, Integer> m = new HashMap();
        while (end < s.length()) {
            if (m.containsKey(s.charAt(end))) {
                //update the start
                start = Math.max(start, m.get(s.charAt(end)));
            }
            ans = Math.max(ans, end - start + 1);
            m.put(s.charAt(end), end + 1);
            end++;
        }
        return ans;
    }
}
View Code

5. Longest Palindromic Substring -- No

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.
Example:

Input: "cbbd"

Output: "bb"
View Code

枚举中间位置,O(n2).

或DP, 或转成求s与s的转置的lcs, 但注意特例abcadeabca这种情况。

class Solution {
public:
    string longestPalindrome(string s) {
        int start = 0;
        int maxlen = 0;
        int n = s.size();
        for (int i = 0; i < n; i++) {
            int oddlen = expan(s, i, i);
            int evenlen = expan(s, i, i+1);
            int len = max(oddlen, evenlen);
            if (len > maxlen) {
                start = i - (len-1) / 2;
                maxlen = len;
            }
        }
        return s.substr(start, maxlen);
    }
private:
    int expan(string s, int i, int j) {
        int l = i;
        int r = j;
        int n = s.size();
        while (l >= 0 && r < n && s[l] == s[r]) {
            l--;
            r++;
        }
        return r-l-1;
    }
};
View Code

11. Container With Most Water -- No

given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.
View Code

从一堆竖在二维平面的棍子中两根使与X轴组成的水杯容量最大。 两个指针往里缩即可。

1st: 看错题,以为是单调栈找面积。

class Solution {
public:
    int maxArea(vector<int>& height) {
        int l = 0;
        int r = height.size()-1;
        int maxarea = 0;
        while (l < r) {
            int area = min(height[l], height[r]) * (r-l);
            maxarea = max(area, maxarea);
            if (height[l] < height[r]) {
                l++;
            } else {
                r--;
            }
        }
        return maxarea;
    }
};
View Code

419. Battleships in a Board --No

iven an 2D board, count how many different battleships are in it. The battleships are represented with 'X's, empty slots are represented with '.'s. You may assume the following rules:

You receive a valid board, made of only battleships or empty slots.
Battleships can only be placed horizontally or vertically. In other words, they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column), where N can be of any size.
At least one horizontal or vertical cell separates between two battleships - there are no adjacent battleships.
Example:
X..X
...X
...X
In the above board there are 2 battleships.
Invalid Example:
...X
XXXX
...X
This is an invalid board that you will not receive - as battleships will always have a cell separating between them.
Follow up:
Could you do it in one-pass, using only O(1) extra memory and without modifying the value of the board?
View Code

思路:在每个连续X的最后时 +1即可。

public class Solution {
    public int countBattleships(char[][] board) {
        if (board == null || board.length == 0) {
            return 0;
        }
        int row = board.length;
        int col = board[0].length;
        int count = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (board[i][j] == '.') {
                    continue;
                }
                if (j > 0 && board[i][j - 1] == 'X') {
                    continue;
                }
                if (i >0 && board[i - 1][j] == 'X') {
                    continue;
                }
                count++;
            }
        }
        return count;
    }
}
View Code

 658. Find K Closest Elements

Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.

Example 1:
Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5], k=4, x=-1
Output: [1,2,3,4]
Note:
The value k is positive and will always be smaller than the length of the sorted array.
Length of the given array is positive and will not exceed 104
Absolute value of elements in the array and x will not exceed 104
View Code

思路:二分找到x在数组中的位置然后向两边扩展

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        int index = std::lower_bound(arr.begin(), arr.end(), x) - arr.begin();
        if (index == arr.size()) {
            return vector<int> (arr.end()-k, arr.end());
        }
        if (index == 0) {
            return vector<int> (arr.begin(), arr.begin()+k);
        }
        int lo = max(index-k, 0);
        int hi = min(index + k, (int)arr.size()-1);
        while (hi - lo > k-1) {
            if (abs(x-arr[lo]) > abs(x-arr[hi])) {
                lo++;
            } else {
                hi--;
            }
        }
        return vector<int> (arr.begin()+lo, arr.begin()+hi+1);
    }
};
View Code

 

posted @ 2016-12-21 10:36  hxidkd  阅读(163)  评论(0编辑  收藏  举报