面试笔试杂项积累-leetcode 6-10

来源:互联网 发布:云计算hadoop实战视频 编辑:程序博客网 时间:2024/05/14 17:50

刷刷刷

6.3-Longest Substring Without Repeating Characters-Difficulty: Medium

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

思路

这道题是求最大连续的字符个数,博主一开始还以为是求不同字符的个数,结果怎么提交都不成功,呵呵呵,知道了题意就很简单了,两个循环,一个检查是否有重复字符,一个循环所有字符,在循环所有字符中,检测并判断是否重复。如果不重复则把当前字符加到一个temp临时string中,并用temp.Length与Max比较(max为储存当前最大长度的int),大的话则max更新。如果重复,通过第一个循环,也就是下面代码的check函数,返回重复字符位置,剪去temp中重复字符(包括重复字符之前的所有字符)

public class Solution {  public int LengthOfLongestSubstring(string s)    {        int max = 0;        string temp = "";        int temp_int = 0;        for (int i = 0; i < s.Length; i++)        {            temp_int = check(temp, s[i]);            temp += s[i];            if (temp_int == -1)            {                if (temp.Length > max)                    max = temp.Length;            }            else            {                    temp = temp.Substring(temp_int+1, temp.Length-temp_int-1);            }        }        return max;    }    int check(string str, char temp)    {        for (int i = 0; i < str.Length; i++)        {            if (str[i] == temp)                return i;        }        return -1;    }}

7.4-Median of Two Sorted Arrays-Difficulty: Hard

There are two sorted arrays nums1 andnums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

思路

Binary Search

参考:

http://blog.csdn.net/yutianzuijin/article/details/11499917/

http://blog.csdn.net/xuyze/article/details/45198757

http://blog.csdn.net/zxzxy1988/article/details/8587244

public class Solution { double findKth(int[] a, int m, int[] b, int n, int k, int a_temp, int b_temp)    {        if (m > n)            return findKth(b, n, a, m, k, b_temp, a_temp);        if (m == 0)            return b[b_temp + k - 1];        if (k == 1)            return (a[a_temp + 0] < b[b_temp + 0]) ? a[a_temp + 0] : b[b_temp + 0];        //divide k into two parts          int pa = (k / 2 < m) ? k / 2 : m, pb = k - pa;        if (a[a_temp + pa - 1] < b[b_temp + pb - 1])            return findKth(a, m - pa, b, n, k - pa, a_temp + pa, b_temp);        else if (a[a_temp + pa - 1] > b[b_temp + pb - 1])            return findKth(a, m, b, n - pb, k - pb, a_temp, b_temp + pb);        else            return a[a_temp + pa - 1];      }    public double FindMedianSortedArrays(int[] nums1, int[] nums2)    {        int m = nums1.Length;        int n = nums2.Length;        int total = m + n;        if ((total & 0x1) != 0)            return findKth(nums1, m, nums2, n, total / 2 + 1, 0, 0);        else            return (findKth(nums1, m, nums2, n, total / 2, 0, 0)                    + findKth(nums1, m, nums2, n, total / 2 + 1, 0, 0)) / 2;    }}

8.5-Longest Palindromic Substring-Difficulty: Medium

Given a string S, find the longest palindromic substring inS. You may assume that the maximum length ofS is 1000, and there exists one unique longest palindromic substring.

思路

一开始自己造方法虽能实现功能但是超时,最后使用DP通过

public class Solution {    public string LongestPalindrome(string s) {     if (s == null || s.Length == 0)            return null;        int start = 0;        int end = 0;        int len = 0;        bool[,] dp = new bool[s.Length, s.Length];        for (int i = s.Length - 1; i >= 0; i--) {            for (int j = i; j < s.Length; j++) {                if (i == j || (s[i] == s[j] && j - i < 2)                        || (s[i] == s[j] && dp[i + 1,j - 1])) {                    dp[i,j] = true;                    if (j - i + 1 > len) {                        len = j - i;                        start = i;                        end = j + 1;                    }                }             }        }         return s.Substring(start, end-start);    }}


9.7-Reverse Integer-Difficulty: Easy

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

方法一

思路

把数反过来,博主第一个想到的方法是用string,再循环反向输入,故就用此方法,要注意正负号的情况,要把负数的负号去掉再反过来,第一次完成时欠考虑,没有考虑超出int的情况,int的最大值为2147483647,最小值为-2147483648,所以判断正负时把int a = -int.MinValue也是不行的,此时a还是int.MinValue。解决这个问题就把int.MinValue单拿出来判断,其余全与int.MaxValue比较即可

public class Solution {    public int Reverse(int x) {        string str = "";        string str_fin = "";        if (x == int.MinValue)            return 0;        str = ((x > 0 ? +1 : -1) * x).ToString();        for (int i = str.Length - 1; i > -1; i--)        {            str_fin += str[i];        }        if (int.MaxValue > long.Parse(str_fin))            return (x > 0 ? +1 : -1) * int.Parse(str_fin);        else return 0;    }}

方法二

思路

不依赖string,求出int每一位再赋值,依然存在最大值最小值问题,,也是一种笨方法,


    public int Reverse(int x)//法2    {        if (x == int.MinValue)            return 0;        int negative = 1;        if (x < 0)        {            negative = -1;            x = -x;        }        long y = x % 10;        while (x / 10 != 0)        {            x /= 10;            y *= 10;            y += x % 10;        }        if (y > int.MaxValue)        {            return -1;        }        else        {            return (int)(negative * y);        }}

10.8-String to Integer (atoi)-Difficulty: Easy

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

方法一

思路

刚开始看到题目时,感觉很简单,后来因为隐含条条框框太多而数次没有通过感觉心烦意乱,遂在代码上修修补补改成下面这个样子,

说起条框

1.首先要默默的把空格去掉再比对,

2.“-123123”,“+1243123”要可以容忍+-号

3.“123a345”要取a前面的数字

4.超过int范围要返回极值,int的最大值为2147483647,最小值为-2147483648

5.会出现"+-213"的情况,需要加额外判断注意

上图证明条框4

第一次出现这个博主傻傻的以为leetcode出问题了,遂加上对MaxValue+1的判断,随后又出现这个问题

才明白怎么回事

。。。总之不细心是不行啊,条框陷阱多

博主本次直接用string操作,把string转换为ascII码然后加以判断,然后转换int,,(总感觉老依赖c#的string现成的函数的这个习惯不太好)

public class Solution {    public int MyAtoi(string str)    {            str = str.Trim();        if (str.Length == 0 )            return 0; �      System.Text.ASCIIEncoding asciiEncoding; int intAsciiCode = 0;        bool sign = false;        for (int i = 0; i < str.Length; i++)        {            asciiEncoding = new System.Text.ASCIIEncoding();            intAsciiCode = (int)asciiEncoding.GetBytes(str)[i];            if (i == 0)            {                if (!sign && (intAsciiCode == 43 || intAsciiCode == 45))                {                    if (i != str.Length - 1)                    {                        intAsciiCode = (int)asciiEncoding.GetBytes(str)[i + 1];                        if (intAsciiCode >= 48 && intAsciiCode <= 57)                        {                            sign = true;                            continue;                        }                        else                            return 0;                    }                    else                        return 0;                }                if (intAsciiCode < 48 || intAsciiCode > 57)                {                    return 0;                }            }            if (intAsciiCode < 48 || intAsciiCode > 57)            {                str = str.Substring(0,i);            break;            }        }        if (str.Length == 0 )            return 0;            if(str.Length > 11)           {                  asciiEncoding = new System.Text.ASCIIEncoding();            intAsciiCode = (int)asciiEncoding.GetBytes(str)[0];           if(intAsciiCode == 43)                return int.MaxValue;                  if(intAsciiCode == 45)                return int.MinValue;                   return int.MaxValue;           }        long temp = long.Parse(str);        if (temp > int.MaxValue)        {      return int.MaxValue;        }        if (temp < int.MinValue)        {            return int.MinValue;        }        return int.Parse(str);    }}

方法二

思路

把string转换为char数组再操作,省去转ascII,省事不少

参考:

http://blog.csdn.net/ljiabin/article/details/40508889


  public int Atoi(string str)    {        if (str == null || str.Length == 0) return 0;        char[] arr = str.ToCharArray();        int i = 0;        bool space = false;        bool negative = false;        while (arr[i] == ' ') i++;        if (arr[i] == '-')        {            negative = true;            ++i;        }        if (arr[i] == '+') ++i;        long sum = 0;        for (; i < arr.Length; i++)        {            if (arr[i] == ' ')            {                space = true;            }            else if (space == true)            {                break;            }            else if (arr[i] >= '0' && arr[i] <= '9')            {                sum = sum * 10 + arr[i] - '0';            }            else            {                break;            }        }        return (int)(negative ? -sum : sum);    }  










1 0
原创粉丝点击