[US Giants] 一. String

来源:互联网 发布:python pdf2txt 编辑:程序博客网 时间:2024/06/12 00:05

Longest Common Subarray

Given two strings, find the longest common substring.

Return the length of it.

The characters in substring should occur continuously in original string. This is different with subsequence.

Example

Given A = "ABCD", B = "CBCE", return 2.

Challenge 

O(n x m) time and memory.

思路:二维DP

          f[i][j]表示A以i结尾,B以j结尾时的LCS,例如f[1][3]表示的是"AB"和"CBCE"

          如果i,j 指向位置的字符相同,+1,如果不相同,直接为0,再重新开始找,过程中还要不断记录max

          最后返回max          

public class Solution {    /**     * @param A, B: Two string.     * @return: the length of the longest common substring.     */    public int longestCommonSubstring(String A, String B) {        if(A==null || B==null){            return 0;        }        int[][] f=new int[A.length()+1][B.length()+1];                int max=0;        for(int i=1;i<=A.length();i++){               //A里的每个字符从0开始,虽然这里是1,但后面charAt(i-1)            for(int j=1;j<=B.length();j++){           //都要遍历B里的每个字符做比较,也是从0开始                if(A.charAt(i-1)==B.charAt(j-1)){                    f[i][j]=f[i-1][j-1]+1;            //[i-1][j-1]是上一轮i-1的结果,而[i][j]是这一轮i                }else{                    f[i][j]=0;                }                max=Math.max(max,f[i][j]);            }        }        return max;    }}

Longest Common Subsequence

Given two strings, find the longest common subsequence (LCS).

Your code should return the length of LCS.

Clarification

What's the definition of Longest Common Subsequence?

  • https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
  • http://baike.baidu.com/view/2020307.htm
Example

For "ABCD" and "EDCA", the LCS is "A" (or "D""C"), return 1.

For "ABCD" and "EACB", the LCS is "AC", return 2.

public class Solution {    /**     * @param A, B: Two strings.     * @return: The length of longest common subsequence of A and B.     */    public int longestCommonSubsequence(String A, String B) {        if(A==null || B==null){            return 0;        }                int[][] f=new int[A.length()+1][B.length()+1];        for(int i=1;i<=A.length();i++){            for(int j=1;j<=B.length();j++){                if(A.charAt(i-1)==B.charAt(j-1)){                    f[i][j]=f[i-1][j-1]+1;                }else{                    f[i][j]=Math.max(f[i-1][j],f[i][j-1]);      //上一轮的前一个位置和这一轮的前一个位置                }            }        }                return f[A.length()][B.length()];    }}

Longest Common Prefix

Given k strings, find the longest common prefix (LCP).

Example

For strings "ABCD""ABEF" and "ACEF", the LCP is "A"

For strings "ABCDEFG""ABCEFG" and "ABCEFA", the LCP is "ABC"

分析:找到字符串数组的最长前缀。

例如:{"abc","ahsja","adef"} -> "a"
          {"abc","ahsja","adef","6734"} -> ""
1.先将第一个的整串字符串设为所求,从第二个字符串开始,找公共最长字符串。
  过程:(1) 如果第二个字符串不包含第一个字符串,就依次检查是否包含第一个字符串的子字符串"ab","a"。
             (2)上面的检查如果检查到底都不包含,就返回"",就是字符串从后面依次减少一个字符的结果
                 上面的检查如果包含,就按照过程(1)检查第三个字符串,然后按照结果检查第四个,第五个。。。
2.关于返回"",只要一个字符串完全不一样("6734"),就会返回""
   注意:string.indexOf(pre)==i,说明从string的i(index)个字母开始pre是string的子串
             因此string.indexOf(pre)!=0,说明当前pre和string没有公共prefix
             如果是-1,说明当前pre不是string的子串 

public class Solution {    /**     * @param strs: A list of strings     * @return: The longest common prefix     */    public String longestCommonPrefix(String[] strs) {        if(strs==null|| strs.length==0){              return "";          }            String pre=strs[0];          for(int i=1;i<strs.length;i++){              while(strs[i].indexOf(pre)!=0){                  pre=pre.substring(0,pre.length()-1);              }          }          return pre;        }}

strStr

For a given source string and a target string, you should output the first index(from 0) of target string in source string.

If target does not exist in source, just return -1.

Clarification

Do I need to implement KMP Algorithm in a real interview? Not necessary. When you meet this problem in a real interview, the interviewer may just want to test your basic implementation ability. But make sure your confirm with the interviewer first.

Example

If source = "source" and target = "target", return -1.

If source = "abcdabcdefg" and target = "bcd", return 1.

Challenge 

O(n2) is acceptable. Can you implement an O(n) algorithm? (hint: KMP)

class Solution {    /**     * Returns a index to the first occurrence of target in source,     * or -1  if target is not part of source.     * @param source string to be scanned.     * @param target string containing the sequence of characters to match.     */    public int strStr(String source, String target) {                    //方法一        if(source==null || target==null){            return -1;        }                for(int i=0;i<source.length()-target.length()+1;i++){            int count=0;            for(int j=0;j<target.length();j++){                if(source.charAt(i+j)!=target.charAt(j)){                    break;                }else{                    count++;                }            }            if(count==target.length()){                return i;            }        }        return -1;    }}
class Solution {    /**     * Returns a index to the first occurrence of target in source,     * or -1  if target is not part of source.     * @param source string to be scanned.     * @param target string containing the sequence of characters to match.     */    public int strStr(String source, String target) {                   //方法二        if(source==null || target==null){            return -1;        }                int k=0;        while(k+target.length()<=source.length()){            String temp=source.substring(k,k+target.length());            if(temp.equals(target)){               return k;            }            k++;        }        return -1;    }}

String to Integer II

Implement function atoi to convert a string to an integer.

If no valid conversion could be performed, a zero value is returned.

If the correct value is out of the range of representable values, INT_MAX(2147483647) or INT_MIN (-2147483648) is returned.

Example
"10" => 10"-1" => -1"123123123123123" => 2147483647"1.0" => 1
思路:首先trim字符串前后的空格
如果字符串有正负符号,要取出符号,但只取一个,如果有多个则无法转译,返回0
如果字符串包含0~9以外的字符,只取前面有效的,例如-00123a66,返回-123
如果超出int范围,返回Integer.MAX_VALUE或者Integer.MIN_VALUE
public class Solution {    /**     * @param str: A string     * @return An integer     */    public int atoi(String str) {        if (str==null || str.length()==0){            return 0;        }    str=str.trim();     boolean flag=true;    int i= 0;    if (str.charAt(0) == '-') {                      //如果第一位是符号,i++,while从i=1开始    flag=false;    i++;    } else if (str.charAt(0) == '+') {    i++;    }     double result = 0;    while(i<str.length()){                           //如果开始没符号,while循环从i=0开始        if(str.charAt(i)>='0' && str.charAt(i)<='9'){            result=result*10+(str.charAt(i)-'0');        i++;        }else{            break;        }    }     if (flag==false){        result = -result;    }    if(result > Integer.MAX_VALUE){        return Integer.MAX_VALUE;    }    if(result < Integer.MIN_VALUE){        return Integer.MIN_VALUE;    }    return (int) result;    }}





原创粉丝点击