w**z 发帖数: 8232 | 1 Source Code from Java
/*
* @author Lee Boynton
* @author Arthur van Hoff
* @author Josh Bloch
* @version 1.92, 04/07/06
* @since JDK1.0
*/
/**
* Parses the string argument as a signed integer in the radix
* specified by the second argument. The characters in the string
* must all be digits of the specified radix (as determined by
* whether {@link java.lang.Character#digit(char, int)} returns a
* nonnegative value), except that the first character may be an
* A... 阅读全帖 |
|
e****e 发帖数: 418 | 2
。。
Agree. Here is my code in Java.
public boolean isFind(String s, int n) {
int mid = s.length() / 2;
char midChar = s.charAt( mid );
if ( midChar == ' ' )
return isFind( s.substring( 0, mid ), n ) || isFind( s.
substring( mid + 1, s.length() ), n );
int rightMostLetterIdx = findRightMostLetterIndex( s, mid );
int leftMostLetterIdx = findLeftMostLetterIndex( s, mid );
String midNum = s.substring( leftMostLetterI... 阅读全帖 |
|
f******h 发帖数: 45 | 3 第二题,终于弄懂什么意思了.
贴一个Java版的
public class Solution {
public String countAndSay(int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(n<=0)
return null;
else if(n==1)
return "1";
else{
String str = "1";
while(n>1){
str = convert(str);
n--;
}
return str;
}
}
public String convert(String str){
Strin... 阅读全帖 |
|
k*********6 发帖数: 738 | 4 public class Solution {
public boolean exist(char[][] board, String word) {
// Start typing your Java solution below
// DO NOT write main() function
//DFS
if (word == null || word.length() == 0) return true;
if (board == null || board.length == 0|| board[0].length == 0)
return false;
boolean[][] visited = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i++)
{
for(int j = ... 阅读全帖 |
|
a********y 发帖数: 1262 | 5 private static java.util.Hashtable cache = new java.util.
Hashtable();
public String countAndSay(int n)
{
// Start typing your Java solution below
// DO NOT write main() function
Object result = cache.get(new Integer(n));
if(result != null)
{
return (String)result;
}
if(n == 1)
{
cache.put(new Integer(1), "1");
return "1";
}
e... 阅读全帖 |
|
n******n 发帖数: 567 | 6 但是在eclipse上可以跑。。。。。。。
public String addBinary(String a, String b) {
// Start typing your Java solution below
// DO NOT write main() function
int l = add(a, b,Math.max(a.length(), b.length()));
if(l == 1)
rs+="1";
char[] c= new char[rs.length()];
for(int i = 0; i < rs.length(); i++){
c[i] = rs.charAt(rs.length()-i-1);
}
return String.valueOf(c);
}
String rs = "";
public int add(String a, String... 阅读全帖 |
|
d*********g 发帖数: 154 | 7
我写的这个common prefix 有时候大测试会超时,有时候能过~
public String longestCommonPrefix(String[] strs)
{
String result = "";
if(strs.length == 0) return result;
int smallestLength = Integer.MAX_VALUE;
for(String str : strs)
{
if(str.isEmpty()) return result;
smallestLength = Math.min(smallestLength, str.length());
}
for(int i = 0; i < smallestLength; ++i)
{
if(!isCommonLetter(strs, i)) return result;
result += strs[0].charAt(i);
}
re... 阅读全帖 |
|
e****e 发帖数: 418 | 8 Question 2:
class MatrixPos{
int row;
int col;
}
// 不用Map, 用数组也行。
Map map = new HashMap();
map.put( 'A', new MatrixPos( 0, 0 ) );
...
map.put( 'Z', new MatrixPos( 5, 0 ) );
void func( String s, char c ) {
//不做参数检查了
print( c, s.charAt( 0 ) )
for ( int i = 0; i < s.length() - 1; i++ )
print( s.charAt( 0 ), s.charAt( 1 ) );
}
void print(char s, char e) {
MatrixPos sp = new MatrixPos( map.get( s ) );
MatrixPos ep = new MatrixPos( map.g... 阅读全帖 |
|
c********t 发帖数: 5706 | 9 void compose(String str, char ch) {
if (str == null || str.isEmpty())
return;
travel(ch, str.charAt(0));
System.out.print("output ");
for (int i = 1; i < str.length(); i++) {
travel(str.charAt(i - 1), str.charAt(i));
System.out.print("output ");
}
}
void travel(char a, char b) {
int i = (a - 'A') / 5, j = (a - 'A') % 5;
int m = (b - 'A') / 5, n = (b - 'A') % 5;
if (a == 'Z' && b != 'Z' && b != 'U') {
travel('Z', 'U');
tr... 阅读全帖 |
|
j**7 发帖数: 143 | 10 Amazon的第四道面试题跟CodeEval上面的一道题几乎一样。可惜面试的时候没有检查到
bug.
https://www.codeeval.com/open_challenges/59/
public class Main {
/**
* @param args
*/
static StringBuilder build=new StringBuilder();
public static void main(String[] args) {
// TODO Auto-generated method stub
telephone("4155230");
}
static void telephone(String input)
{
telephone(input,0,"");
build.deleteCharAt(build.length()-1);
System.out.println(build.toString());
}
... 阅读全帖 |
|
a*****a 发帖数: 46 | 11 呀,是我眼花了,但是romantoint也不需要recursion或者那么多if啊。我的意思是,
一般面试题本身不是特别难的,考察的就是细节了。
这是我写的,yuren贴的那个更简洁些。
public int romanToInt(String s) {
HashMap map = new HashMap();
map.put('M', 1000);
map.put('D', 500);
map.put('C', 100);
map.put('L', 50);
map.put('X', 10);
map.put('V', 5);
map.put('I', 1);
int res = 0;
for (int i=0; i
char c = s.charAt(i);
if ((c == 'C' || c == 'X' || c == 'I')
&... 阅读全帖 |
|
z**********r 发帖数: 86 | 12 跟风贴一个我自己写的,java
public String countAndSay(int n) {
// Start typing your Java solution below
// DO NOT write main() function
// we can use recursion
if (n<=0)
{
return new String("");
}
else if (n==1)
{
return new String("1");
}
else
{
String base=countAndSay(n-1);
StringBuffer result=new StringBuffer();
int i=1;
char previous=base.charAt(... 阅读全帖 |
|
a**d 发帖数: 85 | 13 static class Log {
int in,out;
Log(int a,int b) {
in=a;
out=b;
}
}
public String log(Log[] l) {
String[] s=new String[2*l.length];
for(int i=0,j=0;i
s[j++]=l[i].in+"i";
s[j++]=l[i].out+"o";
}
Arrays.sort(s);
LinkedHashMap lh=new LinkedHashMap();
int counter=1;
for(int i=1;i
char cur=s[i].charAt(0),pre=s[i-1].charAt(0);
if(cur!=pre) {
... 阅读全帖 |
|
a**d 发帖数: 85 | 14 static class Log {
int in,out;
Log(int a,int b) {
in=a;
out=b;
}
}
public String log(Log[] l) {
String[] s=new String[2*l.length];
for(int i=0,j=0;i
s[j++]=l[i].in+"i";
s[j++]=l[i].out+"o";
}
Arrays.sort(s);
LinkedHashMap lh=new LinkedHashMap();
int counter=1;
for(int i=1;i
char cur=s[i].charAt(0),pre=s[i-1].charAt(0);
if(cur!=pre) {
... 阅读全帖 |
|
l*n 发帖数: 529 | 15 无聊写了个。a、b都是正数,其他符号的组合可以另写个wrapper函数。
String subtract(String a, String b) {
boolean minus = false;
if (b.length() > a.length() || b.length() == a.length()
&& a.compareTo(b) < 0)
minus = true;
if (minus) {
String tmp = a;
a = b;
b = tmp;
}
int alen = a.length();
int blen = b.length();
StringBuilder sb = new StringBuilder(
new String(new char[a.length()]).replace('\0', '0'));
int carry = 0;
for (int i = 0; i < a.length();... 阅读全帖 |
|
K*******n 发帖数: 607 | 16 大牛能看一下为什么我的解法有一个case总是超时呢?
public class Solution {
public String reverseWords(String s) {
String result = "";
Stack st = new Stack();
for (int i = s.length() -1; i >= 0; i--)
{
if (s.charAt(i) != ' ')
st.push(s.charAt(i));
else
{
while (!st.empty())
result += st.pop();
if (result.length() != 0 && result.charAt(result.length()-1)
!= ' ')
... 阅读全帖 |
|
z***e 发帖数: 58 | 17
从左开始往右遍历 试图找到冒号使得分割?后面的字符串,如a?[...]:[...] 就是找到
: , 找法就是如果碰到一个 ? 就加一碰到: 就减一,这样第一个抵消?和:的也就是0
的:就是要找的冒号。然后对两个[...] 分别递归即可。随便敲了下,将就看吧。
Node createExpression(int start, int end, String str ){
if(right== left) return new Node(str[start]);
int count = 0;
Node node =new Node(str.charAt(start));
int breakIndex = 0;
for(int i = start; i <= end; ++i){
if(str.charAt(i) == '?') count++;
else if(str.charAt(i) == ':')count--;
if(count == 0) { brea... 阅读全帖 |
|
m*****k 发帖数: 731 | 18 抛砖:
public static boolean isAbbr(String s, String abbr){
//internationalization”, “i5a11o1”
if(s==null){
return abbr==null;
}
if(s.length()==0){
return abbr.length()==0;
}
abbr+="A";
int lastCharIdxInAbbr = -1;
int lastCharIdxInS = -1;
for(int i = 0; i
if(Character.isLetter(abbr.charAt(i))){
String numStr = abbr.substring(lastCharIdxInAb... 阅读全帖 |
|
x*******6 发帖数: 262 | 19 贡献一个code,由于没有乘除,只需要记录括号内是否要根据加减改变数字的符号,不
需要使用reverse polish notation解法。
public static int eval(String s, int x) {
String[] exp = s.split("=");
int[] left = helper(exp[0],x);
int[] right = helper(exp[1],x);
return (left[0] - right[0])/(right[1]-right[0]);
}
private static int[] helper(String s, int x) {
boolean positive = true;
Stack re = new Stack();
re.push(false);
int num = 0;
int y = 0;
... 阅读全帖 |
|
s*******h 发帖数: 105 | 20 Java 版,这个题一次过很难那。
public String DeleteDigits(String A, int k) {
// write your code here
if(A.length()<2) return A;
int i=0;
StringBuilder s=new StringBuilder(A);
while(i
if(i>=0&&s.charAt(i)>s.charAt(i+1)){
s.deleteCharAt(i);
k--;
if(k==0) break;
i--;
}
else i++;
}
i=s.length()-1;
while(k>0&&i>-1){
s.deleteC... 阅读全帖 |
|
s*******h 发帖数: 105 | 21 Java 版,这个题一次过很难那。
public String DeleteDigits(String A, int k) {
// write your code here
if(A.length()<2) return A;
int i=0;
StringBuilder s=new StringBuilder(A);
while(i
if(i>=0&&s.charAt(i)>s.charAt(i+1)){
s.deleteCharAt(i);
k--;
if(k==0) break;
i--;
}
else i++;
}
i=s.length()-1;
while(k>0&&i>-1){
s.deleteC... 阅读全帖 |
|
p*****2 发帖数: 21240 | 22
这个行吗?
int curr = 0;
Node dfs(String str){
if(curr >= str.length())
return null;
int i = curr;
while(i
i++;
Node node = new Node(str.substring(curr, i));
curr = i+1;
if(i
node.left = dfs(str);
node.right = dfs(str);
}
return node;
} |
|
p*****2 发帖数: 21240 | 23
这个行吗?
int curr = 0;
Node dfs(String str){
if(curr >= str.length())
return null;
int i = curr;
while(i
i++;
Node node = new Node(str.substring(curr, i));
curr = i+1;
if(i
node.left = dfs(str);
node.right = dfs(str);
}
return node;
} |
|
W***u 发帖数: 81 | 24 用一个stack 扫一遍, 把不valid的 符号存里面,最后再筛一次。 O(n) + O(n)
我理解对了么?
String balance(String par) {
if (par.length() < 1)
return null;
String rlt = "";
Stack upSt = new Stack();
for (int i = 0; i < par.length(); i++) {
char c = par.charAt(i);
if (c == '(' || c == ')') {
if (upSt.isEmpty()) {
upSt.push(i);
} else {
char topChar = par.charAt(upSt.peek()... 阅读全帖 |
|
J*********a 发帖数: 50 | 25 public List findRepeatedDnaSequences(String s) {
// A->00 C->01 G->10 T->11
List res = new ArrayList<>();
Map map = new HashMap<>();
for (int i = 0; i + 10 <= s.length(); i++) {
int key = hashFunc(s.substring(i, i + 10));
if (map.containsKey(key) && !map.get(key)) {
res.add(s.substring(i, i + 10));
map.put(key,true);
} else if (!map.containsKey(key)){
... 阅读全帖 |
|
x******6 发帖数: 46 | 26 题在这儿
http://yuanhsh.iteye.com/blog/2206191
我的解法和博客里的有点不同,不知道有没有忘记考虑什么case,有谁愿意帮我看一下
吗?谢谢!
import java.util.Stack;
public class Solution {
public TreeNode ternary2Tree(String ternary) {
if (ternary.length() == 0) {
return null;
}
Stack stack = new Stack<>();
TreeNode root = new TreeNode(ternary.charAt(0));
stack.push(root);
for (int i = 1; i < ternary.length(); i += 2) {
char operator = ternary.charAt(i);
... 阅读全帖 |
|
k****r 发帖数: 807 | 27 some logic as follows:
helper(s, 0, 0, "", res, new HashSet set);
public void helper(String s, int idx, int blc, String tmp, List res,
Set set) {
if (idx == s.length()) {
if (blc == 0 && !set.contains(tmp)) {
res.add(tmp);
set.add(tmp);
}
return;
}
if (s.charAt(idx) == '(') {
helper(s, idx + 1, blc + 1, tmp + "(", res);
helper(s, idx + 1, blc + 1, tmp, res);
} else if (s.charAt(idx) == ')') ... 阅读全帖 |
|
b***e 发帖数: 1419 | 28 /*
Find all substring palindomes. No dupe.
Vanilla JS. Run it with node.js or in browser console.
*/
function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
};
var p = function(s) {
var prevLookup = {};
var nextLookup = {};
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
if (!prevLookup[c]) {
prevLookup[c] = [];
nextLookup[c] = [];
}
}
for (var i = 0; i <... 阅读全帖 |
|
b***e 发帖数: 1419 | 29 /*
Find all substring palindomes. No dupe.
Vanilla JS. Run it with node.js or in browser console.
*/
function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
};
var p = function(s) {
var prevLookup = {};
var nextLookup = {};
for (var i = 0; i < s.length; i++) {
var c = s.charAt(i);
if (!prevLookup[c]) {
prevLookup[c] = [];
nextLookup[c] = [];
}
}
for (var i = 0; i <... 阅读全帖 |
|
h******6 发帖数: 2697 | 30 我来抛砖引个玉吧。是不是首先还得计算出个dp[][]数组表示i到j是不是chunked
palindrome,后面就跟palindrome partition一样了。所以关键是如何构造那个dp[][]
也就转化为给定一个String,如何判断它是不是chunked palindrome。
boolean isChunkedPalindrome(String s) {
int left = 0, right = s.length() - 1;
LinkedList queue = new LinkedList();
int[] cnt = new int[256];
while (left < right) {
char leftChar = s.charAt(left);
char rightChar = s.charAt(right);
queue.add(rightChar);
cnt[leftChar]++;
cnt[righ... 阅读全帖 |
|
g****j 发帖数: 24 | 31 想用textpane装载一段文字,只有ATCG四种字母,所有的A用绿色,T用红色,等等。
我用document实现了,可是当文字数目多的时候,刷新速度超慢,请问如何解决?
下面是代码
String content="AATGCAGCTAGCTAGCTAGCTA"; //may be over 10000 letters
SimpleAttributeSet attrs = new SimpleAttributeSet();
for(int i=0;i
{
if(content.charAt(i)=='A')
StyleConstants.setBackground(attrs,Color.green);
else if(content.charAt(i)=='T')
StyleConstants.setBackground(attrs,Color.red);
else if(content.charAt(i)=='C')
StyleConstants.setBackground(attrs,Color.blue) |
|
H*****l 发帖数: 1257 | 32 原题是Leetcode上的Palindrome Partitioning
如下:
Given a string s, partition s such that every substring of the partition is
a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
--------------------------------------------------------
请问,dfs函数里,这一小段是什么用处啊?特别是最后的remove..
for(int i=start+1;i<=s.length();i++){
if(isPalin(s,start,i-1)){
al.add(s.substring(start,i));
d... 阅读全帖 |
|
s*****y 发帖数: 897 | 33 Not familiar java, but have question on this:
why
return input.charAt(i) + find(input.substring(0, i) + input.subs
tring(i+1), j);
but not
return input.charAt(i) + find(input.substring(0, i-1) + input.subs
tring(i+1), j);
substring(i+1), j); |
|
y****n 发帖数: 192 | 34 有那么夸张吗?
private static Boolean isPrefix(String prefix, String s1) {
if(prefix.length()>s1.length())
return false;
for(int i=0; i
boolean t = prefix.charAt(i)==s1.charAt(i);
if (false==t)
return false;
else if (true==t&& i == prefix.length()-1)
return true;
}
return false;
} |
|
y****n 发帖数: 192 | 35 有那么夸张吗?
private static Boolean isPrefix(String prefix, String s1) {
if(prefix.length()>s1.length())
return false;
for(int i=0; i
boolean t = prefix.charAt(i)==s1.charAt(i);
if (false==t)
return false;
else if (true==t&& i == prefix.length()-1)
return true;
}
return false;
} |
|
c*********n 发帖数: 1057 | 36 1是不是用DP?
I[i][j] = min # of char added to make substring from i to j become
palindrome
S[i][j] = the corresponding palindrome string converted from substring i to
j
then I[i][i]=0;I[i+1][i]=0
I[i][j] = min( I[i][j-1], I[i+1][j]) + 1 //if charAt[i] != charAt[j]
= I[i+1][j-1] //otherwise
S[i][j] modified accordingly
return S[0][N] |
|
r******r 发帖数: 700 | 37 我这个方法很笨。 谁能写个 O(n) 的? 这个好像也是被 facebook 考了的。
// civic
private static boolean isCharPalindrome(String test) {
String stripped = test.toLowerCase().replaceAll("[^0-9a-zA-Z]", "");
for(int i = 0; i < stripped.length() / 2; i++) {
if(stripped.charAt(i) != stripped.charAt(stripped.length() - 1 -
i)) {
return false;
}
}
return true;
}
// ILLINOISURB
public static String longestPrefixPalindrome(String test){
Stri... 阅读全帖 |
|
g**********y 发帖数: 14569 | 38 String很好啊,对越界情况容易处理。
public String add(String a, String b) {
StringBuffer c = new StringBuffer();
StringBuffer sa = new StringBuffer(a).reverse();
StringBuffer sb = new StringBuffer(b).reverse();
int N = Math.max(sa.size(), sb.size());
int r = 0;
for (int i=0; i
int bit1 = sa.size()>i? sa.charAt(i)-'0' : 0;
int bit2 = sb.size()>i? sb.charAt(i)-'0' : 0;
int sum = r + bit1 + bit2;
c.append(sum%10);
r = sum/10;
}
if (r > 0) c.append(r);
return c.reverse().toString();
} |
|
p*****2 发帖数: 21240 | 39 写了一个练练手。
import java.util.*;
class Node
{
Node[] children=new Node[26];
public Node Set(char c)
{
Node node=new Node();
children[c-'a']=node;
return node;
}
public Node Get(char c)
{
return children[c-'a'];
}
}
class Trie
{
Node root=new Node();
public void Add(String word)
{
int i=0;
Node node=root;
while(i
{
char c=word.charAt(i);
if(node.Ge... 阅读全帖 |
|
p*****2 发帖数: 21240 | 40 写了一个练练手。
import java.util.*;
class Node
{
Node[] children=new Node[26];
public Node Set(char c)
{
Node node=new Node();
children[c-'a']=node;
return node;
}
public Node Get(char c)
{
return children[c-'a'];
}
}
class Trie
{
Node root=new Node();
public void Add(String word)
{
int i=0;
Node node=root;
while(i
{
char c=word.charAt(i);
if(node.Ge... 阅读全帖 |
|
z******w 发帖数: 36 | 41 用dfs的方法实现了一下,dfs有些改动,需要记录当前栈内已经访问的节点,发现当前点和路
径不符立即返回false,否则递归处理相邻的元素。一旦发现路径走完立即返回true
-----------------------------
import java.util.HashSet;
import java.util.Set;
public class FindPath {
public boolean findPath(String[] m, String path) {
if (path.length() == 0) return true;
for (int i = 0; i < m.length; i ++) {
for (int j = 0; j < m[0].length(); j ++) {
Set set = new HashSet();
if (dfs(m, i, j, path, 0, set))
return true;
}
}
return false;
}
private boolean dfs(String[] m, int ... 阅读全帖 |
|
y*****z 发帖数: 9 | 42 这个是概率题。。
先生成 4个bit的 二进制 true代表1,false代表0
这样我们能生成0-15的 等概率的 distribution
然后 [0,15] 当中 选[0,10] -->[0,2](true), [3,9](false)
public class Solution {
/**
* @param args
*/
public void doit(){
int iterate = 10000000;
boolean valve = true;
StringBuilder s = new StringBuilder();
while (valve) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < 4; i++) {
if (Math.random() < 0.5) str.append('1');
... 阅读全帖 |
|
y*****z 发帖数: 9 | 43 这个是概率题。。
先生成 4个bit的 二进制 true代表1,false代表0
这样我们能生成0-15的 等概率的 distribution
然后 [0,15] 当中 选[0,10] -->[0,2](true), [3,9](false)
public class Solution {
/**
* @param args
*/
public void doit(){
int iterate = 10000000;
boolean valve = true;
StringBuilder s = new StringBuilder();
while (valve) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < 4; i++) {
if (Math.random() < 0.5) str.append('1');
... 阅读全帖 |
|
p*****2 发帖数: 21240 | 44 这是我的代码。
public class test
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String s=in.next();
String u=in.next();
int row=u.length();
int col=s.length();
boolean[][] matrix=new boolean[row][col];
for(int i=0;i
{
char c=u.charAt(i);
for(int j=0;j
if(s.charAt(j)==c)
matrix[i][j]=true;
}
... 阅读全帖 |
|
p*****2 发帖数: 21240 | 45 这是我的代码。
public class test
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String s=in.next();
String u=in.next();
int row=u.length();
int col=s.length();
boolean[][] matrix=new boolean[row][col];
for(int i=0;i
{
char c=u.charAt(i);
for(int j=0;j
if(s.charAt(j)==c)
matrix[i][j]=true;
}
... 阅读全帖 |
|
m*******m 发帖数: 82 | 46 Interview Questions:
Redefine a function (signature given) to write data to a new replacement for
an antiquated database (which you previously designed)
Answer Question:
Write a function to return the longest common prefix between two strings.
//java code
String GetCommonPrefix(String a, String b)
{
char[] aChar = a.toCharArray();
char[] bChar = b.toCharArray();
int startIndex = 0;
//choose short length as the end index
int needLength= aChar.length>bChar.length?bChar.length:aChar.lengt... 阅读全帖 |
|
w***o 发帖数: 109 | 47 我也凑个热闹
public String multiply(String num1, String num2) {
int n = num1.length();
int m = num2.length();
int[] result = new int[n + m];
for(int i = m - 1; i >= 0; i--) {
int k = n + i;
int a = num2.charAt(i) - '0';
for(int j = n - 1; j>= 0; j--) {
int x = a * (num1.charAt(j) - '0');
x += result[k];
result[k--] = x % 10;
result[k] += x / 10;
}
}
... 阅读全帖 |
|
c*****e 发帖数: 3226 | 48 那也不需要阿。 比如:((()
扫描到 最后一个"(", count = 3; len = 3;
扫描下一个")", count = 2; len = 4;
因此,最长的字串就应该是 len - count = 2;
再比如:((()()
接着上面的例子,
扫描到 最后一个"(", count = 3; len = 5;
扫描下一个")", count = 2; len = 6;
因此,最长的字串就应该是 len - count = 4;
因此扫描2遍似乎不需要,只要cout < 0 的时候重新reset 就好了。
code:
public static int longestValidParentheses(String s) {
int n = s.length();
int maxl = 0;
int count = 0;
int len = 0;
for(int i = 0;i < n;i++){
if(s.charAt(i) == '('){
count++;
len++... 阅读全帖 |
|
c*****e 发帖数: 3226 | 49 那也不需要阿。 比如:((()
扫描到 最后一个"(", count = 3; len = 3;
扫描下一个")", count = 2; len = 4;
因此,最长的字串就应该是 len - count = 2;
再比如:((()()
接着上面的例子,
扫描到 最后一个"(", count = 3; len = 5;
扫描下一个")", count = 2; len = 6;
因此,最长的字串就应该是 len - count = 4;
因此扫描2遍似乎不需要,只要cout < 0 的时候重新reset 就好了。
code:
public static int longestValidParentheses(String s) {
int n = s.length();
int maxl = 0;
int count = 0;
int len = 0;
for(int i = 0;i < n;i++){
if(s.charAt(i) == '('){
count++;
len++... 阅读全帖 |
|
w***o 发帖数: 109 | 50 拿这个练练DP:
public int longestValidParentheses(String s) {
int n = s.length();
int[] dp = new int[n+1];
int max = 0;
for(int i = n-2; i >= 0; i--) {
if(s.charAt(i) == '(') {
int j = i+1+dp[i+1];
if(j < n && s.charAt(j) == ')') {
dp[i] = 2+dp[i+1]+dp[j+1];
max = Math.max(max, dp[i]);
}
}
}
return max;
} |
|