LeetCode_String_Easy
来源:互联网 发布:网络交流软件 编辑:程序博客网 时间:2024/04/29 21:59
String Easy
Zigzag Conversion
The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H NA P L S I I GY I R
And then read line by line: “PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
class Solution {public: string convert(string s, int numRows) { int len=s.length(); string res; if(numRows==1 || numRows>=len) return s; string ctmp=""; int itmp=0; int count=0; int tt=0; for(int i=0;i<numRows;i++){ count=i; itmp =1; while(count<len){ ctmp=s.at(count); res.append(ctmp); if((i==0) || (i==(numRows-1))){ tt=2*(numRows-1); } else{ if(itmp%2==1) tt=2*((numRows-1)-i); else tt=2*i; itmp++; } count=count+tt; } } return res; }};
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) { string res; char ts='0'; int lenA=a.length(); int lenB=b.length(); string tts=""; int diff=abs(lenA-lenB); while(diff--){ if(lenA>lenB) b.insert(0,"0"); else a.insert(0,"0"); } int len=max(lenA,lenB); while(len>0){ len--; if( a.at(len)!=b.at(len)){ if(ts=='0'){ ts='0'; res.insert(0,"1"); }else if(ts=='1'){ ts='1'; res.insert(0,"0"); } } else if(a.at(len)==b.at(len) && ts=='1'){ if(a.at(len)=='0'){ ts='0'; res.insert(0,"1"); } if(a.at(len)=='1'){ ts='1'; res.insert(0,"1"); } }else if(a.at(len)==b.at(len) && ts=='0'){ if(a.at(len)=='0'){ ts='0'; res.insert(0,"0"); } if(a.at(len)=='1'){ ts='1'; res.insert(0,"0"); } } } if(ts=='1') res.insert(0,"1"); return res; }};
Valid Parentheses
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
class Solution {public: bool isValid(string s) { stack<char> st; for (int i=0;i<s.size();i++){ if ((s[i]=='(') ||(s[i]=='[') ||(s[i]=='{')) {st.push(s[i]);} else{ if (st.empty()){return false;} if ((s[i]==')') && (st.top()!='(')) {return false;} if ((s[i]=='{') && (st.top()!='}')) {return false;} if ((s[i]=='[') && (st.top()!=']')) {return false;} st.pop(); } } return st.empty(); }};
- LeetCode_String_Easy
- 常见HTTP状态码整理
- C#中的线程(二)线程同步基础
- iperf 测试带宽
- mysqldump报错'The user specified as a definer ('root'@'%') does not exist when using LOCK TABLES'
- sql 修改表结构
- LeetCode_String_Easy
- windows手动添加软件自启动项
- 关于Android自启动管理的相关知识点
- 自定义分页方法 1.1版
- ubuntu 下安装jad反编译器,显示源代码
- 连续英文、数字换行
- C#中的线程(三)使用多线程
- java mysql 批量处理
- Thinkphp的URL规则,伪静态,路由,重写,伪静态,生成及其调试