字符串

简单题


14.Longest Common Prefix 舍弃

求一组string的最长公共前缀
class Solution {  
public:  
    string longestCommonPrefix(vector<string>& strs) {  
        int n=strs.size();  
        string result;  
        if(n==0) return result;  
        string flag=strs[0];  //已经排好序
        int m=flag.size();  
        for(int i=0;i<m;i++)  
        {  
            for(int j=1;j<n;j++)  
        {  
            if(flag[i]!=strs[j][i])   
            return result;  
        }  
            result.push_back(flag[i]);  
        }  
        return result;  
  
    }  
};  


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.

class Solution {
public:
    int lengthOfLastWord(string s) {
        int count=0;
        //遇到空格就一直往后走,如果遇到另外一个字母,count变成1,如果到了结尾,返回count
        int n=s.size();
        if(n==0) return 0;
        for(int i=0;i<n;i++)
        {
            if(s[i]!=' ') count++;
            else
            {
                while(i<n&&s[i]==' ') i++;
                if(i>=n) return count;
                else count=1;
            }
        }
        return count;
    }
};
67. Add Binary
给定两个二进制字符串,返回他们的和

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

翻转两个字符串,得到最后的字符串再翻转回来。出错了。

class Solution {
public:
    string addBinary(string a, string b) {
        reverse(a.begin(),a.end());
        reverse(b.begin(),b.end());
        int aSize=a.size(),bSize=b.size();
        int i=0;
        string res;
        int temp=0;
        int sum=0;
        while(i<aSize||i<bSize)
        {
            sum=sum+temp+(i<aSize?cti(a[i]):0);
            sum+=i<bSize?cti(b[i]):0;
            temp=0;
            if(sum==0) res.push_back('0');
            else if(sum==1) res.push_back('1');
            else if(sum==2) 
            {
                res.push_back('1');
                temp=1;
            }
            i++;
            sum=0;
        }
        if(temp==1)
            res.push_back('1');
        reverse(res.begin(),res.end());
        return res;
    }
    int cti(char a){
        if(a=='0') return 0;
        if(a=='1') return 1;
    }
};

正确代码:
class Solution {
public:
    string addBinary(string a, string b) {
        reverse(a.begin(),a.end());
        reverse(b.begin(),b.end());
        int an=a.size();
        int bn=b.size();
        int i=0;
        string res;
        int next=0;
        char zero='0',one='1';
        while(i<an||i<bn)
        {
            char temp='0';
            if(i<an)
                temp+=a[i]=='1'?1:0;
            if(i<bn)
                temp+=b[i]=='1'?1:0;
            if(next==1)
                temp+=1;
            if(temp=='0')
            {
                res.push_back(zero);
                next=0;
            }
            else if(temp=='1')
            {
                res.push_back(one);
                next=0;
            }
            else if(temp=='2')
            {
                res.push_back(zero);
                next=1;
            }
            else 
            {
                res.push_back(one);
                next=1;
            }
            i++;
        }
        if(next==1)
            res.push_back(one);
        return string(res.rbegin(),res.rend());
    }
};
简洁方法:
class Solution {
public:
    string addBinary(string a, string b) {
        int i=a.size()-1,j=b.size()-1;
        string s="";
        int c=0;
        while(i>=0||j>=0||c==1)
        {
            c+=i>=0?a[i--]-'0':0;
            c+=j>=0?b[j--]-'0':0;
            s=char(c%2+'0')+s;//使用string的相加特性
            c/=2;
        }
        return s;
    }
};


变种:
43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

看答案:

class Solution {
public:
    string multiply(string num1, string num2) {
        string res(num1.size()+num2.size(),'0');
        for(int i=num1.size()-1;i>=0;i--)
        {
            int carry=0;
            for(int j=num2.size()-1;j>=0;j--)
            {
                int temp=(res[i+j+1]-'0')+(num1[i]-'0')*(num2[j]-'0')+carry;
                res[i+j+1]=temp%10+'0';
                carry=temp/10;
            }
            res[i]+=carry;
        }
        size_t firstzero=res.find_first_not_of("0");
        if(firstzero!=string::npos)
            return res.substr(firstzero);
        return "0";

    }
};





551 Student Attendance Record I43.7%Easy  重点是判断语句的运用!!!

You are given a string representing an attendance record for a student. The record only contains the following three characters:

  1. 'A' : Absent.
  2. 'L' : Late.
  3. 'P' : Present.

A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).

You need to return whether the student could be rewarded according to his attendance record.

Example 1:

Input: "PPALLP"
Output: True

Example 2:

Input: "PPALLL"
Output: False
我的思路:使用标志位处理
class Solution {
public:
    bool checkRecord(string s) 
    {
        //三个P,两个A,设置三个标志位,第一个标志位与A出现两次有关,第二个与P出现两次有关,第三个当第二个标志位是true的时候,第三次出现则为true
        int size=s.size();
        bool flagA=false;
        bool flagPTwo=false;
        bool flagPThree=false;
        for(int i=0;i<size;i++)
        {
            if(s[i]=='A')
            {
                if(flagA) return false;
                else flagA=true;
                //注意,在这个判断分支中需要把L相关的两个标志位改变,这个地方很容易忽略
                flagPTwo=false;
                flagPThree=false;
            }
            else if(s[i]=='L')
            {
                if(flagPThree) //说明之前已经有两个了
                    return false;
                else if(flagPTwo)//之前已经有一个了
                {
                    flagPThree=true;
                }
                else //之前没有P出现
                {
                    flagPTwo=true;
                }
            }
            else if(s[i]=='P')//当前不是P也不是A
            {
                flagPTwo=false;
                flagPThree=false;
            }
        }
        //全部循环完成之后,说明没有出现上述情况
        return true;
    }
};

别人的方法2:if 和if else的差别很明显,前面我的思路使用if else语句,下面的方法用了并行的两个if语句分别判断A和L,非常简洁。

class Solution {
public:
    bool checkRecord(string s) 
    {
        //下面代码的好处是:因为L出现三次,使用int变量更好,如果使用标志,需要两个
        //另一个好处是,第一个if else的else包含了s[i]=='A'的情况,大大简化代码
        int a=0;//统计A出现的次数
        int l=0;//统计L连续出现的次数
        for(int i=0;i<s.size();i++)
        {
            if(s[i]=='L') l++;
            else l=0;
            if(s[i]=='A') a++;
            if(a>=2||l>2) return false;
        }
        return true;
    }
};



541 Reverse String II44.1%Easy 翻转字符串2

给定k,翻转每2k个字符的前k个,如果剩余字符不够k,那就全部旋转,如果不够2k个那么就旋转K个
自己的思路:需要写一个额外的旋转字符串来处理。
旋转的过程遵循两次旋转的方法,

//理解好题目很重要
class Solution {
public:
    string reverseStr(string s, int k) {
        int size=s.size();
        for(int i=0;i<size;)
        {
            int n=size-i;
            if(n>=2*k)
            {
                reverse(s,i,k);
                i+=2*k;
            }
            else if(n<2*k&&n>=k)
            {
                reverse(s,i,k);
                break;//注意这里要写break
            }
            else 
            {
                reverse(s,i,n);
                break;
            }
        }
        return s;
    }
    //以下是旋转的处理函数
    void reverse(string &s,int first,int k){//字符串,起始位置,需要旋转的数
        int last=first+k-1;
        while(first<last)
        {
            int temp=s[first];
            s[first++]=s[last];
            s[last--]=temp;
        }
    }
};


344 Reverse String59.0%Easy 翻转字符串


class Solution {
public:
    string reverseString(string s) {
        int size=s.size();
        if(size<=1) return s;
        for(int i=0;i<=size/2-1;i++){
            char temp=s[i];
            s[i]=s[size-i-1];
            s[size-i-1]=temp;
        }
        return s;
    }
};

58 Length of Last Word31.8%Easy


537 Complex Number Multiplication64.5%Medium

Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
思路:这个题目思路并不难,考察的是对字符串的字符和数字的转换

下面的代码没有调试成功

class Solution {
public:
    string complexNumberMultiply(string a, string b) {
        int reala=0,ima=0,realb=0,imb=0;
        changeToNumber(a,reala,ima);
        changeToNumber(b,realb,imb);
        int resultreal=reala*realb-ima*imb;
        int resultim=reala*imb+realb*ima;
        return changeToString(resultreal,resultim);
        
    }
    void changeToNumber(string & a,int& real,int& im ){
        int i=0;
        string realString;
        bool neg=false;
        if(a[0]=='-')  {
            neg=true;
            i++;}
        while(a[i]!='+')
            realString.push_back(a[i++]);
        real=stoi(realString)*(neg?-1:1);
        neg=false;
        realString.clear();
        i++;
        if(a[0]=='-') 
        {
            neg=true;
            i++;
        }
        while(i<a.size()){
            realString.push_back(a[i++]);
        }
        im=stoi(realString)*(neg?-1:1);
    }
    string changeToString(int real,int im){
        string a;
        string temp;
        if(real<0) 
         {
             a.push_back('-');
             real*=-1;
         }
        ToStringMy(real,temp);
        a+=temp;
        temp.clear();
        a.push_back('+');
         if(im<0) 
         {
             a.push_back('-');
             im*=-1;
         }
        ToStringMy(im,temp);
        a+=temp;
        a.push_back('i');
        return a;
        
    }
    void ToStringMy(int real,string& temp){
        
        stringstream ss;
        ss<<real;
        ss>>temp;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值